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?
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?
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());
}
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?