Search code examples
javasortinghashmapkey-valuetreemap

how to sort a map by key when the values are the same?


I'm currently sorting the map by value, but I couldn't think on how I would have it sorted by key for the cases that I have the same value.

Currently it works like this:

public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        @Override
        public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
            return e2.getValue().compareTo(e1.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}

My output is something like this: (AA,10), (CC,5), (BB,5)

I'm trying to achieve this: (AA,10), (BB,5), (CC,5)


Solution

  • You could check in your Comparator if the values are the same and if so compare the keys. Here is your adapted method:

    public static <K extends Comparable<? super K>, V extends Comparable<? super V>> Map<K, V> newSortMapByValue(Map<K, V> map) {
            List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
            Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
                @Override
                public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
                    // Check if values are the same
                    if (e1.getValue().equals(e2.getValue()))
                        // Compare e1 to e2, because A should be first element
                        return e1.getKey().compareTo(e2.getKey());
                    else
                        // Compare e2 to e1, because largest number should be first
                        return e2.getValue().compareTo(e1.getValue());
                }
            });
    
            Map<K, V> result = new LinkedHashMap<>();
            for (Map.Entry<K, V> entry : list) {
                result.put(entry.getKey(), entry.getValue());
            }
            return result;
        }
    
    

    Example main:

        public static void main(String[] args) {
            Map<String, Integer> map = new HashMap<>();
            map.put("AA",10);
            map.put("CC",5);
            map.put("BB",5);
            map.put("DD",15);
            map.put("ZZ",15);
    
            System.out.println(map);
            Map sortedMap = newSortMapByValue(map);
            System.out.println(sortedMap);
        }
    

    Output:

    {AA=10, CC=5, BB=5, DD=15, ZZ=15}
    {DD=15, ZZ=15, AA=10, BB=5, CC=5}