i have treemap and i sort it on value with code bellow. how can i get results as treemap again?
static <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> entriesSortedByValues(
Map<K, V> map) {
SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(
new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res != 0 ? res : 1;
}
});
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
You're creating a TreeSet
, whereas, you need to create a TreeMap
. The comparator which you pass to TreeMap
, will use the map
passed as parameter, to fetch the value and compare them.
Change your method to:
static <K, V extends Comparable<? super V>> TreeMap<K, V> entriesSortedByValues(final Map<K, V> map) {
TreeMap<K, V> sortedEntries = new TreeMap<K, V>(new Comparator<K>() {
@Override
public int compare(K o1, K o2) {
return map.get(o1).compareTo(map.get(o2));
}
});
sortedEntries.putAll(map);
return sortedEntries;
}
Tested with:
public static void main(String args[]) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 3);
map.put(3, 1);
map.put(5, 6);
map.put(2, 10);
// Prints: {3=1, 1=3, 5=6, 2=10}
System.out.println(entriesSortedByValues(map));
}