Sort map by value using lambdas and streams

前端 未结 4 379
逝去的感伤
逝去的感伤 2020-12-08 09:37

I\'m new to Java 8, not sure how to use streams and it\'s methods to sort. If I have map as below, how to sort this map by value to take only top 10 entries using Java 8.

相关标签:
4条回答
  • 2020-12-08 09:59

    You can always start reading the documentation and some tutorials.

    map.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) 
            .limit(10) 
            .forEach(System.out::println); // or any other terminal method
    

    Reference

    http://www.leveluplunch.com/java/examples/sort-order-map-by-values/

    0 讨论(0)
  • 2020-12-08 10:01

    If you want sort by integer or float value of value object

    Map<String,Person> map = new HashMap<>();
    map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
    map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
    map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));
    

    You can use,

    Map<String,Person> sortedNewMap = map.entrySet().stream().sorted((e1,e2)->
            Integer.compare(e1.getValue().getAge(), e2.getValue().getAge()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (e1, e2) -> e1, LinkedHashMap::new));
    
    0 讨论(0)
  • 2020-12-08 10:06

    See the stack flow thread here and example here

    Map<String,Person> map = new HashMap<>();
    map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
    map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
    map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));
    
    Map<String,Person> sortedNewMap = map.entrySet().stream().sorted((e1,e2)->
            e1.getValue().getLocation().compareTo(e2.getValue().getLocation()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (e1, e2) -> e1, LinkedHashMap::new));
    sortedNewMap.forEach((key,val)->{
        System.out.println(key+ " = "+ val.toString());
    });
    
    0 讨论(0)
  • 2020-12-08 10:07
    List<Map.Entry<String, Integer>> entries = newArrayList(map.entrySet());
    Collections.sort(entries, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));
    List<Map.Entry<String, Integer>> top10 = entries.subList(0, Math.min(entries.size(), 10));
    
    0 讨论(0)
提交回复
热议问题