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

一世执手 提交于 2019-11-29 11:38:50

问题


I have a list that I need to custom sort and then convert to a map with its Id vs. name map.

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.


回答1:


You have Collectors.toMap for that purpose :

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<Long, String> map = 
    list.stream()
        .sorted(Comparator.comparing(Building::getName))
        .collect(Collectors.toMap(Building::getId,
                                  Building::getName,
                                  (v1,v2)->v1,
                                  LinkedHashMap::new));



回答2:


Use toMap() of java.util.stream.Collectors



来源:https://stackoverflow.com/questions/29721095/converting-a-collection-to-map-by-sorting-it-using-java-8-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!