如何在 Java 8 中将 Map 转换为 List

2022-01-22 00:00:00 java-8 java java-stream

如何在 Java 8 中将 Map 转换为 List>?

How to convert a Map<String, Double> to List<Pair<String, Double>> in Java 8?

我写了这个实现,但是效率不高

I wrote this implementation, but it is not efficient

Map<String, Double> implicitDataSum = new ConcurrentHashMap<>();
//....
List<Pair<String, Double>> mostRelevantTitles = new ArrayList<>();
implicitDataSum.entrySet()
               .stream()
               .sorted(Comparator.comparing(e -> -e.getValue()))
               .forEachOrdered(e -> mostRelevantTitles.add(new Pair<>(e.getKey(), e.getValue())));

return mostRelevantTitles;

我知道它应该使用 .collect(Collectors.someMethod()) 工作.但我不明白该怎么做.

I know that it should works using .collect(Collectors.someMethod()). But I don't understand how to do that.

推荐答案

好吧,你想将 Pair 元素收集到一个 List 中.这意味着您需要将 Stream<Map.Entry<String, Double>> 映射到 Stream<Pair<String, Double>>.

Well, you want to collect Pair elements into a List. That means that you need to map your Stream<Map.Entry<String, Double>> into a Stream<Pair<String, Double>>.

这是通过 map 操作:

This is done with the map operation:

返回一个流,该流包含将给定函数应用于该流的元素的结果.

Returns a stream consisting of the results of applying the given function to the elements of this stream.

在这种情况下,该函数是将 Map.Entry 转换为 Pair 的函数.

In this case, the function will be a function converting a Map.Entry<String, Double> into a Pair<String, Double>.

最后,您希望将其收集到一个 List 中,这样我们就可以使用内置的 toList() 收集器.

Finally, you want to collect that into a List, so we can use the built-in toList() collector.

List<Pair<String, Double>> mostRelevantTitles = 
    implicitDataSum.entrySet()
                   .stream()
                   .sorted(Comparator.comparing(e -> -e.getValue()))
                   .map(e -> new Pair<>(e.getKey(), e.getValue()))
                   .collect(Collectors.toList());

请注意,您可以将比较器 Comparator.comparing(e -> -e.getValue()) 替换为 Map.Entry.comparingByValue(Comparator.reverseOrder())代码>.

Note that you could replace the comparator Comparator.comparing(e -> -e.getValue()) by Map.Entry.comparingByValue(Comparator.reverseOrder()).

相关文章