1

I'm trying to sort a ConcurrentSkipListMap by value in Java, here is my code :

ConcurrentSkipListMap<String,Float> cslMap = new ConcurrentSkipListMap(new Comparator() {
    public int compare(Object o1,Object o2) {
        return ((Comparable)((Map.Entry)(o1)).getValue()).compareTo(((Map.Entry)(o2)).getValue());
    }
});
cslMap_Map.put("B",0.2f);
cslMap_Map.put("A",0.1f);
cslMap_Map.put("C",1f);

Got an error message when compiling it:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map$Entry

What's the correct way to do it ?

Thanks for the answers, but in it's Java doc, it says "The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time", so how to supply it with a Comparator that sort by its values ?

Frank
  • 30,590
  • 58
  • 161
  • 244
  • 1
    There is no correct way to do it. There is no data structure in Java that supports `ConcurrentMap` and also sorts by value. – Louis Wasserman Nov 08 '13 at 17:23
  • 1
    That doesn't make any sense... how could you lookup anything in the skiplist by key if it's not sorted by key? – Affe Nov 08 '13 at 17:23
  • 3
    The `Comparator` is for the keys, not for the entries of the map... – Luiggi Mendoza Nov 08 '13 at 17:24
  • If you used generics correctly, the compiler told you at compile time that it is nonsense what you do. If you don't use it you can spend lots of hours with you try-and-get-`ClassCastException` approach. – Holger Nov 08 '13 at 19:22

1 Answers1

0

A SkipList must be sorted by key in order to work. It is really a lot more like a tree than a hashmap in the way it looks things up. (The name 'Map' in the java implementation is to indicate that it implements the Map interface, should not imply it is a cousin of HashMap or ConcurrentHashMap as an actual data structure.)

It "Skips" to different points in the list based on the result of comparing the lookup key to the current node-level, and narrows down where in the list the key you're looking for is. If it's not sorted, you'll just dead-end or jump around forever and never find anything.

Affe
  • 47,174
  • 11
  • 83
  • 83