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

前端 未结 2 1922
礼貌的吻别
礼貌的吻别 2020-12-31 04:12

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 map = new Link         


        
相关标签:
2条回答
  • 2020-12-31 05:00

    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));
    
    0 讨论(0)
  • 2020-12-31 05:14

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

    0 讨论(0)
提交回复
热议问题