Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Last active October 4, 2017 18:07
Show Gist options
  • Save shailrshah/b8e7902d74d1dd2bee39831b30e82ce4 to your computer and use it in GitHub Desktop.
Save shailrshah/b8e7902d74d1dd2bee39831b30e82ce4 to your computer and use it in GitHub Desktop.
Functions to sort a Map by either keys or values, either ascending or descending
import java.util.Map;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.LinkedHashMap;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.Comparator;
class MapSort {
// Works with HashMaps, TreeMaps and LinkedHashMaps because they all implement Map
static void printMap(Map<String, Integer> map, String message) {
System.out.println(message);
map.forEach((k, v) -> System.out.println(k + "\t" + v));
System.out.println();
}
static Map<String, Integer> sortMapByKeys(Map<String, Integer> unsortedMap, boolean isAscending) {
// TreeMap sorts by Keys
// CRUD times are O(lg n)
Map<String, Integer> sortedMap;
if(isAscending)
sortedMap = new TreeMap<>();
else
sortedMap = new TreeMap<>(Collections.reverseOrder());
unsortedMap.forEach((k, v) -> sortedMap.put(k,v));
return sortedMap;
}
static Map<String, Integer> sortMapByValues(Map<String, Integer> unsortedMap, boolean isAscending) {
// LinkedHashMap maintains a doubly-linked list running through all its entries
// Insertion order is maintained
// CRUD operations are O(1)
Map<String, Integer> sortedMap = new LinkedHashMap<>();
if(isAscending)
unsortedMap.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(e -> sortedMap.put(e.getKey(), e.getValue()));
else
unsortedMap.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).forEach(e -> sortedMap.put(e.getKey(), e.getValue()));
return sortedMap;
}
public static void main(String[] args) {
// HashMap does not sort the entries
// CRUD times are O(1)
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Bob", 22);
hashMap.put("Charlie", 9);
hashMap.put("Alice", 8);
hashMap.put("Eric", 75);
hashMap.put("Dan", 51);
printMap(hashMap, "Original Map");
Map<String, Integer> sortedMapByKeys = sortMapByKeys(hashMap, true);
printMap(sortedMapByKeys, "Sorted Map By Keys - Ascending");
Map<String, Integer> sortedMapByKeysDesc = sortMapByKeys(hashMap, false);
printMap(sortedMapByKeysDesc, "Sorted Map By Keys - Descending");
Map<String, Integer> sortedMapByValues = sortMapByValues(hashMap, true);
printMap(sortedMapByValues, "Sorted Map By Values - Ascending");
Map<String, Integer> sortedMapByValuesDesc = sortMapByValues(hashMap, false);
printMap(sortedMapByValuesDesc, "Sorted Map By Values - Descending");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment