How to sort Map values by key in Java?

后端 未结 15 2193
野性不改
野性不改 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:09

    Just in case you don't wanna use a TreeMap

    public static Map<Integer, Integer> sortByKey(Map<Integer, Integer> map) {
            List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
            list.sort(Comparator.comparingInt(Map.Entry::getKey));
            Map<Integer, Integer> sortedMap = new LinkedHashMap<>();
            list.forEach(e -> sortedMap.put(e.getKey(), e.getValue()));
            return sortedMap;
        }
    

    Also, in-case you wanted to sort your map on the basis of values just change Map.Entry::getKey to Map.Entry::getValue

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

    In Java 8 you can also use .stream().sorted():

    myMap.keySet().stream().sorted().forEach(key -> {
            String value = myMap.get(key);
    
            System.out.println("key: " + key);
            System.out.println("value: " + value);
        }
    );
    
    0 讨论(0)
  • 2020-11-22 09:11

    Using the TreeMap you can sort the map.

    Map<String, String> map = new HashMap<>();        
    Map<String, String> treeMap = new TreeMap<>(map);
    for (String str : treeMap.keySet()) {
        System.out.println(str);
    }
    
    0 讨论(0)
  • 2020-11-22 09:15

    Using Java 8:

    Map<String, Integer> sortedMap = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
    
    0 讨论(0)
  • 2020-11-22 09:16

    Short answer

    Use a TreeMap. This is precisely what it's for.

    If this map is passed to you and you cannot determine the type, then you can do the following:

    SortedSet<String> keys = new TreeSet<>(map.keySet());
    for (String key : keys) { 
       String value = map.get(key);
       // do something
    }
    

    This will iterate across the map in natural order of the keys.


    Longer answer

    Technically, you can use anything that implements SortedMap, but except for rare cases this amounts to TreeMap, just as using a Map implementation typically amounts to HashMap.

    For cases where your keys are a complex type that doesn't implement Comparable or you don't want to use the natural order then TreeMap and TreeSet have additional constructors that let you pass in a Comparator:

    // placed inline for the demonstration, but doesn't have to be a lambda expression
    Comparator<Foo> comparator = (Foo o1, Foo o2) -> {
            ...
        }
    
    SortedSet<Foo> keys = new TreeSet<>(comparator);
    keys.addAll(map.keySet());
    

    Remember when using a TreeMap or TreeSet that it will have different performance characteristics than HashMap or HashSet. Roughly speaking operations that find or insert an element will go from O(1) to O(Log(N)).

    In a HashMap, moving from 1000 items to 10,000 doesn't really affect your time to lookup an element, but for a TreeMap the lookup time will be about 3 times slower (assuming Log2). Moving from 1000 to 100,000 will be about 6 times slower for every element lookup.

    0 讨论(0)
  • 2020-11-22 09:16
    List<String> list = new ArrayList<String>();
    Map<String, String> map = new HashMap<String, String>();
    for (String str : map.keySet()) {
     list.add(str);
    }
    Collections.sort(list);
    for (String str : list) {
     System.out.println(str);
    }
    
    0 讨论(0)
提交回复
热议问题