How to remove an element from sorted ConcurrentNavigableMap with custom Comparator



The problem is when it’s time to remove an element. I tried on unsorted ConcurrentNavigableMap and the element was successfully removed. But on the sorted one cannot be removed. Does anyone have any idea what the problem?

private ConcurrentNavigableMap<String, Post> registeredPost=new ConcurrentSkipListMap<String,Post>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int i1=Integer.parseInt(o1);
                int i2=Integer.parseInt(o2);
                if(i1 >= i2){
                    return -1;
                }else{
                    return 1;
                }
            };
        });

public int deletePost(String postId) {
for(Iterator<Entry<String, Post>> it= registeredPost.entrySet().iterator();it.hasNext();) {
            Entry<String,Post> e=it.next();
            String temp=e.getKey();
            
            if(temp.compareTo(postId)==0) {
                registeredPost.remove(e.getKey());
            }
          return 0; 
        }
 return 1;
}

Answer

Some issues:

Equality of keys is determined by the comparator, your Comparator doesn’t take equal elements into account. You must return 0 if i1 == i2 – or use the Comparator helper methods: Comparator.comparingInt(Integer::parseInt). If you do not specify a comparator, the String.compareTo method is used, which handles it correctly.

You should remove Elements with it.remove() method – otherwise you will get a ConcurrentModificationException.

The return statement is in the wrong place, as it has been pointed out.



Source: stackoverflow