How to sort Map values by key in Java?

后端 未结 15 2209
野性不改
野性不改 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<String,String> sample = new HashMap<>();  // push some values to map  
    Map<String, String> newMapSortedByKey = sample.entrySet().stream()
                        .sorted(Map.Entry.<String,String>comparingByKey().reversed())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
    Map<String, String> newMapSortedByValue = sample.entrySet().stream()
                            .sorted(Map.Entry.<String,String>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<String, String> 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));
    
    0 讨论(0)
  • 2020-11-22 09:18

    Just use TreeMap

    new TreeMap<String, String>(unsortMap);
    

    Be aware that the TreeMap is sorted according to the natural ordering of its 'keys'

    0 讨论(0)
  • 2020-11-22 09:18

    If you already have a map and would like to sort it on keys, simply use :

    Map<String, String> treeMap = new TreeMap<String, String>(yourMap);
    

    A complete working example :

    import java.util.HashMap;
    import java.util.Set;
    import java.util.Map;
    import java.util.TreeMap;
    import java.util.Iterator;
    
    class SortOnKey {
    
    public static void main(String[] args) {
       HashMap<String,String> hm = new HashMap<String,String>();
       hm.put("3","three");
       hm.put("1","one");
       hm.put("4","four");
       hm.put("2","two");
       printMap(hm);
       Map<String, String> treeMap = new TreeMap<String, String>(hm);
       printMap(treeMap);
    }//main
    
    public static void printMap(Map<String,String> map) {
        Set s = map.entrySet();
        Iterator it = s.iterator();
        while ( it.hasNext() ) {
           Map.Entry entry = (Map.Entry) it.next();
           String key = (String) entry.getKey();
           String value = (String) entry.getValue();
           System.out.println(key + " => " + value);
        }//while
        System.out.println("========================");
    }//printMap
    
    }//class
    
    0 讨论(0)
提交回复
热议问题