package mightypork.utils.objects; import java.util.*; import java.util.Map.Entry; /** * Map sorting utils * * @author MightyPork */ public class MapSort { /** * Sort a map by keys, maintaining key-value pairs. * * @param map map to be sorted * @param comparator a comparator, or null for natural ordering * @return linked hash map with sorted entries */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static Map sortByKeys(Map map, final Comparator comparator) { final List keys = new LinkedList<>(map.keySet()); if (comparator == null) { Collections.sort(keys); } else { Collections.sort(keys, comparator); } // LinkedHashMap will keep the keys in the order they are inserted // which is currently sorted on natural ordering final Map sortedMap = new LinkedHashMap<>(); for (final K key : keys) { sortedMap.put(key, map.get(key)); } return sortedMap; } /** * Sort a map by values, maintaining key-value pairs. * * @param map map to be sorted * @param comparator a comparator, or null for natural ordering * @return linked hash map with sorted entries */ @SuppressWarnings("rawtypes") public static Map sortByValues(Map map, final Comparator comparator) { final List> entries = new LinkedList<>(map.entrySet()); Collections.sort(entries, new Comparator>() { @Override public int compare(Entry o1, Entry o2) { if (comparator == null) return o1.getValue().compareTo(o2.getValue()); return comparator.compare(o1.getValue(), o2.getValue()); } }); // LinkedHashMap will keep the keys in the order they are inserted // which is currently sorted on natural ordering final Map sortedMap = new LinkedHashMap<>(); for (final Map.Entry entry : entries) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } }