javatreemapsortedmap

How to set custom comparator in Java Map of Map?


Map<Character, TreeMap<Integer, String>> topElems = new HashMap<Character, TreeMap<Integer, String>  > ();

How to set a custom comparator for the TreeMap in the above statement?

Something like:

Map<Character, TreeMap<Integer, String>> topElems = new HashMap<Character, TreeMap<Integer, String> ((x, y) -> y - x)  > ();

Solution

  • You're attempting to set the Comparator in the type argument, which is invalid syntax. The type arguments only specify the types, they aren't actual instances. What you would need to do is use the correct Comparator for each TreeMap you put into the outer Map:

    Map<Character, TreeMap<Integer, String>> map = new HashMap<>();
    
    TreeMap<Integer, String> treeMap = new TreeMap<>((x, y) -> y - x);
    map.put('A', treeMap);
    

    Note you cannot force, via the compiler, that every TreeMap use the same Comparator implementation.