通过使用 java 8 流对其进行排序来将集合转换为 Map
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29721095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a collection to Map by sorting it using java 8 streams
提问by Mohammad Adnan
I have a list that I need to custom sort and then convert to a map with its Id vs. name map.
我有一个列表,我需要对其进行自定义排序,然后将其转换为带有 Id 与名称映射的映射。
Here is my code:
这是我的代码:
Map<Long, String> map = new LinkedHashMap<>();
list.stream().sorted(Comparator.comparing(Building::getName)).forEach(b-> map.put(b.getId(), b.getName()));
I think this will do the job but I wonder if I can avoid creating LinkedHashMap
here and use fancy functional programming to do the job in one line.
我认为这会完成这项工作,但我想知道我是否可以避免LinkedHashMap
在此处创建并使用花哨的函数式编程在一行中完成这项工作。
回答by Eran
You have Collectors.toMap
for that purpose :
Collectors.toMap
为此,您必须:
Map<Long, String> map =
list.stream()
.sorted(Comparator.comparing(Building::getName))
.collect(Collectors.toMap(Building::getId,Building::getName));
If you want to force the Map implementation that will be instantiated, use this :
如果要强制将实例化的 Map 实现,请使用以下命令:
Map<Long, String> map =
list.stream()
.sorted(Comparator.comparing(Building::getName))
.collect(Collectors.toMap(Building::getId,
Building::getName,
(v1,v2)->v1,
LinkedHashMap::new));
回答by mushfek0001
Use toMap()
of java.util.stream.Collectors
使用toMap()
的java.util.stream.Collectors