/*
* Une collection TreeMap est par défaut triée avec ses clés, mais si vous avez besoin de trier une TreeMap
* par valeurs, Java fournit un moyen en utilisant la classe Comparator.
*/
package TreeMap;
import java.util.*;
/**
*
* @author fabrice
*/
class Tri_par_valeurs {
// Static method which return type is Map and which extends Comparable.
// Comparable is a comparator class which compares values associated with two keys.
public static <K, V extends Comparable<V>> Map<K, V> valueSort(final Map<K, V> map) {
// compare the values of two keys and return the result
Comparator<K> valueComparator = (K k1, K k2) -> {
int comparisonResult = map.get(k1).compareTo(map.get(k2));
if (comparisonResult == 0) return 1;
else return comparisonResult;
};
// Sorted Map created using the comparator
Map<K, V> sorted = new TreeMap<K, V>(valueComparator); // create a new empty TreeMap ordered according to the given comparator
sorted.putAll(map); // copy mappîngs of "map" into "sorted" an order them by value
return sorted;
}
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
// Feed the Map
map.put(1, "Anshu");
map.put(5, "Rajiv");
map.put(3, "Chhotu");
map.put(2, "Golu");
map.put(4, "Sita");
// Display elements before sorting
Set unsortedSet = map.entrySet();
Iterator i1 = unsortedSet.iterator();
while (i1.hasNext()) {
Map.Entry mapEntry = (Map.Entry) i1.next();
System.out.println("Key: " + mapEntry.getKey() + " - Value: " + mapEntry.getValue());
}
// call method valueSort() and assign the output to sortedMap
Map sortedMap = valueSort(map);
System.out.println(sortedMap);
// Display elements after sorting
Set sortedSet = sortedMap.entrySet();
Iterator i2 = sortedSet.iterator();
while (i2.hasNext()) {
Map.Entry mapEntry = (Map.Entry) i2.next();
System.out.println("Key: " + mapEntry.getKey() + " - Value: " + mapEntry.getValue());
}
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter