-1

Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?

I have a treemap<Integer,Float>. How can I sort the the map on float point number?

Is there any quick way? or I have to write the comparator for the map?

Community
  • 1
  • 1
John
  • 827
  • 5
  • 15
  • 25
  • 1
    @OP: Take note of the caveats on the accepted answer of the duplicate question. There are a _lot_ of ways in which that solution doesn't work. – Louis Wasserman Dec 14 '12 at 18:42

2 Answers2

5

In practice, you can't (correctly, reliably) sort a Map implementation by the values. (The implementations you might see claiming otherwise are hackish, unreliable, and behave really weirdly -- rejecting duplicate values, throwing exceptions on attempts to look at keys not in the map, getting unrecoverably corrupted if the backing map changes...)

Instead, sort the list of entries explicitly:

List<Map.Entry<Integer, Float>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Float>>() {
  public int compare(Map.Entry<Integer, Float> e1, Map.Entry<Integer, Float> e2){
    return e1.getValue().compareTo(e2.getValue());
  }
});

If you liked, you could then put this into a LinkedHashMap:

Map<Integer, Float> sortedMap = new LinkedHashMap<Integer, Float>();
for (Map.Entry<Integer, Float> entry : list) {
  sortedMap.put(entry.getKey(), entry.getValue());
}
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
2

Easiest solution might be to use LinkedHashMap instead, and sort it by values. See this: How to sort a LinkedHashMap by its value class's field?

Community
  • 1
  • 1
hyde
  • 60,639
  • 21
  • 115
  • 176