如何在Java 8中将Map转换为List [英] How to convert Map to List in Java 8
问题描述
如何将 Map< String,Double>
转换为列表< Pair< String,Double>>
在Java 8中?
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.
推荐答案
嗯,你要收集对
元素到列表
。这意味着您需要将 Stream< Map.Entry< String,Double>>
映射到流< 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< String,Double> <的函数/ code>进入
对< String,Double>
。
In this case, the function will be a function converting a Map.Entry<String, Double>
into a Pair<String, Double>
.
最后,你要收集那个进入列表
,这样我们就可以使用内置的 toList()
collector。
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())
by Map.Entry.comparingByValue(Comparator.reverseOrder())
。
Note that you could replace the comparator Comparator.comparing(e -> -e.getValue())
by Map.Entry.comparingByValue(Comparator.reverseOrder())
.
这篇关于如何在Java 8中将Map转换为List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!