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
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
