Skip to content

Instantly share code, notes, and snippets.

@wytten
Created April 16, 2021 15:40
Show Gist options
  • Save wytten/de8ad75cc1a231dbb7112a28eafe6212 to your computer and use it in GitHub Desktop.
Save wytten/de8ad75cc1a231dbb7112a28eafe6212 to your computer and use it in GitHub Desktop.
Given a Map, sort it by values to create a new LinkedHashMap that preserves this order
import java.util.*;
import java.util.Map.Entry;
/**
* Given a Map, sort it by values to create a new LinkedHashMap that preserves this order
*
* From: https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values
* And: https://mkyong.com/java/how-to-sort-a-map-in-java/
*/
public class MapUtil {
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
List<Entry<K, V>> list = new ArrayList<>(map.entrySet());
//list.sort(Entry.comparingByValue());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1,
Map.Entry<K, V> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<K, V> result = new LinkedHashMap<>();
for (Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment