Sometimes we want to sort a Map by its values, as opposed to its keys. Occasionally this can be done by reversing the Map as in the example here, but more likely you need to sort a List of the entries. Why? Because values could be duplicated, in which case entries would be lost on reversal, since a Map can't contain duplicate keys. Here is a way of sorting, The code is HERE. Update: the Java streaming API makes this simpler and that approach is also shown below.
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
public class MapValueSort {
public static void main(String[] args) {
Map<String, String> m = new HashMap<String, String>();
m.put("zero", "0");
m.put("nil", "0");
m.put("one", "1");
List<Map.Entry<String, String>> entries = MapValueSort.sortByValue(m);
System.out.println(entries);
// With the Java streaming API
List<Map.Entry<String, String>> eSorted = m.entrySet().
stream().
sorted(Comparator.comparing(Map.Entry::getValue)).
toList();
System.out.println(eSorted);
}
@SuppressWarnings("unchecked")
public static <K, V extends Comparable> List<Map.Entry<K, V>> sortByValue(
Map<K, V> map) {
List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(map.size());
entries.addAll(map.entrySet());
Collections.sort(entries,
new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
return entries;
}
}
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
public class MapValueSort {
public static void main(String[] args) {
Map<String, String> m = new HashMap<String, String>();
m.put("zero", "0");
m.put("nil", "0");
m.put("one", "1");
List<Map.Entry<String, String>> entries = MapValueSort.sortByValue(m);
System.out.println(entries);
// With the Java streaming API
List<Map.Entry<String, String>> eSorted = m.entrySet().
stream().
sorted(Comparator.comparing(Map.Entry::getValue)).
toList();
System.out.println(eSorted);
}
@SuppressWarnings("unchecked")
public static <K, V extends Comparable> List<Map.Entry<K, V>> sortByValue(
Map<K, V> map) {
List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(map.size());
entries.addAll(map.entrySet());
Collections.sort(entries,
new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
return entries;
}
}