TreeMap sort by value

后端 未结 9 873
闹比i
闹比i 2020-11-22 02:44

I want to write a comparator that will let me sort a TreeMap by value instead of the default natural ordering.

I tried something like this, but can\'t find out what

9条回答
  •  花落未央
    2020-11-22 03:34

    In Java 8:

    LinkedHashMap sortedMap = 
        map.entrySet().stream().
        sorted(Entry.comparingByValue()).
        collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                                 (e1, e2) -> e1, LinkedHashMap::new));
    

提交回复
热议问题