How to convert Map to List in Java 8(如何在 Java 8 中将 Map 转换为 List)
问题描述
如何在 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()).
这篇关于如何在 Java 8 中将 Map 转换为 List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 8 中将 Map 转换为 List
基础教程推荐
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01
