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
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
