Home » Java » java – Create SortedMap with Custom Compartor<Map.Entry>-Exceptionshub

java – Create SortedMap with Custom Compartor<Map.Entry>-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment


I tried several things it appears TreeMap supports only sorting by keys. I attempted to work around it by code I found online but, it gave me StackOverflowError error. Why do I need the ability to compare by Map.Entry specifically. One is to compare by values, another is to compare values by a custom comparator such as shuffling or reverse order.

Also intended behavior is once this map is constructed any object added to the sorted map will use the comparator every time it gets added. The tutorials online use LinkedHashMap and converting into an array and then it gets stuck in that set order adding anything to that object will not keep the comparator ordering

public static <K, V> SortedMap<K, V> sort(Map<K, V> map, Comparator c)
    TreeMap<K, V> ordered = new TreeMap<K, V>(c);
    if(c instanceof ComparatorValue)
        ((ComparatorValue)c).map = ordered;
    return ordered;

the comparator class

public SortedMap map;
public ComparatorValue(SortedMap instance)
    this.map = instance;

public int compare(Object key1, Object key2) 
    Comparable val1 = (Comparable) this.map.get(key1);
    Comparable val2 = (Comparable) this.map.get(key2);
    if(val1 == val2)
        return 1;
    return val1.compareTo(val2); 

the error code

Exception in thread "main" java.lang.StackOverflowError
at java.util.TreeMap.getEntryUsingComparator(Unknown Source)
at java.util.TreeMap.getEntry(Unknown Source)
at java.util.TreeMap.get(Unknown Source)
at jml.evilnotch.lib.simple.ComparatorValue.compare(ComparatorValue.java:17)
How to&Answers: