In this article we will see how to sort a map by keys and values, we will sort the map by keys and by values using Java 8. We have example data that contains map of "Employee" id and object.
class Employee {
	private int id;
	private String name;

	// Getter Setters, constructor and toString()

}


1) Sort a Map by keys in Java 8

		Map<Integer, Employee> employeesMap = new HashMap<>();
		employeesMap.put(3, new Employee(3, "Zenny"));
		employeesMap.put(1, new Employee(1, "John"));
		employeesMap.put(2, new Employee(2, "Ben"));
		System.out.println("Map after sorting by keys");

		Map<Integer, Employee> sortedMapByKey = employeesMap.entrySet().stream().sorted(Map.Entry.comparingByKey())
				.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
						LinkedHashMap::new));

		sortedMapByKey.forEach((k, v) -> System.out.println("Key: " + k + "Value:" + v));

Output: Output of above code will look something like this:


Map after sorting by keys
Key: 1 Value:Employee [id=1, name=John]
Key: 2 Value:Employee [id=2, name=Ben]
Key: 3 Value:Employee [id=3, name=Zenny]


2) Sort a Map by values in Java 8

		Map<Integer, Employee> employeesMap = new HashMap<>();
		employeesMap.put(3, new Employee(3, "Zenny"));
		employeesMap.put(1, new Employee(1, "John"));
		employeesMap.put(2, new Employee(2, "Ben"));
		System.out.println("Map after sorting by values (name)");

		Map<Integer, Employee> sortedMapByKey = employeesMap.entrySet().stream()
				.sorted(new Comparator<Entry<Integer, Employee>>() {
					@Override
					public int compare(Entry<Integer, Employee> o1, Entry<Integer, Employee> o2) {
						return o1.getValue().getName().compareTo(o2.getValue().getName());
					}
				}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
						LinkedHashMap::new));
		sortedMapByKey.forEach((k, v) -> System.out.println("Key: " + k + " Value:" + v));
	
Output: Output of above code will look something like this:


Map after sorting by values (name)

Key: 2 Value:Employee [id=2, name=Ben]
Key: 1 Value:Employee [id=1, name=John]
Key: 3 Value:Employee [id=3, name=Zenny]

  • By Techburps.com
  • Oct 6, 2018
  • Java 8