fork(3) download
  1. import java.util.Comparator;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.SortedSet;
  5. import java.util.TreeSet;
  6.  
  7. public class Main {
  8.  
  9. public static void main(String[] args) {
  10.  
  11. Map<String, String> map = new HashMap<String, String>();
  12.  
  13. map.put("My", "World!");
  14. map.put("Hello", "World!");
  15. map.put("This", "World!");
  16. map.put("Test", "X!");
  17.  
  18. System.out.println("The original map: " + map);
  19.  
  20. // sort the
  21. SortedSet<Map.Entry<String, String>> sorted = entriesSortedByValues(map);
  22.  
  23. // print the value based sorted set
  24. System.out.println("The sorted set: " + sorted);
  25.  
  26. // check that for example the first element is in the set
  27. if (!sorted.contains(sorted.iterator().next()))
  28. throw new RuntimeException("The set doesn't contain the first element?");
  29. }
  30.  
  31. static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
  32. SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
  33. new Comparator<Map.Entry<K,V>>() {
  34. @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
  35. int res = e1.getValue().compareTo(e2.getValue());
  36. return res != 0 ? res : 1; // Special fix to preserve items with equal values
  37. }
  38. }
  39. );
  40. sortedEntries.addAll(map.entrySet());
  41. return sortedEntries;
  42. }
  43. }
Runtime error #stdin #stdout 0.03s 245632KB
stdin
Standard input is empty
stdout
The original map: {Test=X!, My=World!, This=World!, Hello=World!}
The sorted set:   [My=World!, This=World!, Hello=World!, Test=X!]