简体   繁体   English

通过使用java 8流对集合进行排序,将集合转换为Map

[英]Converting a collection to Map by sorting it using java 8 streams

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并使用花哨的函数式编程来完成一行中的工作。

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));

使用java.util.stream.Collectors toMap()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM