I know answer to this question has been provided in many variants but I couldn't find it for my specific query.
I want to have a map which is sorted by values and I need to get it created before I put data into it. I came up with below code to create it
private Map<String, Integer> mapUserScore = new ConcurrentSkipListMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int i1=mapUserScore.get(o2);
int i2=mapUserScore.get(o1);
if(mapUserScore.get(o2)!=null && mapUserScore.get(o1)!=null){
int compare = mapUserScore.get(o2)-(mapUserScore.get(o1));
if(compare==0)compare=-1;
return compare;
}else
return 0;
}
});
So basically I want entries in map sorted by integer values in descending order so that highest scorers are on top. However upon doing this when the first key-value pair is inserted, the program exits with below exception
Exception in thread "Thread-0" java.lang.StackOverflowError
at java.util.concurrent.ConcurrentSkipListMap.comparable(ConcurrentSkipListMap.java:658)
at java.util.concurrent.ConcurrentSkipListMap.doGet(ConcurrentSkipListMap.java:821)
at java.util.concurrent.ConcurrentSkipListMap.get(ConcurrentSkipListMap.java:1626)
Upon tracing, I found that line int i1=mapUserScore.get(o2) results in this exception. Can anyone please help me to understand what could be the reason of stackoverflow here? I am thinking that because before any item is stored in the map, code is trying to obtain it by using get() method to sort it and hence it goes into some recursive calls and results in exception.