How to sort Map values by key in Java?

后端 未结 15 2358
野性不改
野性不改 2020-11-22 08:26

I have a Map that has strings for both keys and values.

Data is like following:

\"question1\", \"1\"
\"question9\", \"1\"
\"que

15条回答
  •  孤独总比滥情好
    2020-11-22 09:17

    Provided you cannot use TreeMap, in Java 8 we can make use of toMap() method in Collectorswhich takes following parameters:

    • keymapper: mapping function to produce keys
    • valuemapper: mapping function to produce values
    • mergeFunction: a merge function, used to resolve collisions between values associated with the same key
    • mapSupplier: a function which returns a new, empty Map into which the results will be inserted.

    Java 8 Example

    Map sample = new HashMap<>();  // push some values to map  
    Map newMapSortedByKey = sample.entrySet().stream()
                        .sorted(Map.Entry.comparingByKey().reversed())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
    Map newMapSortedByValue = sample.entrySet().stream()
                            .sorted(Map.Entry.comparingByValue().reversed())
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new));
    

    We can modify the example to use custom comparator and to sort based on keys as:

    Map newMapSortedByKey = sample.entrySet().stream()
                    .sorted((e1,e2) -> e1.getKey().compareTo(e2.getKey()))
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new));
    

提交回复
热议问题