/**
* @author lautturi.com
* Java example: how to sort a hashmap/treemap/linkedmapmap
in natural/ascending/descending/reverse order in java
*/
import java.util.*;
import java.util.stream.Collectors;
public class Lautturi {
public static void main(String[] args) {
HashMap<String, Integer> fruits = new HashMap<>();
fruits.put("Apple", 21);
fruits.put("Banana", 12);
fruits.put("Cherry", 15);
fruits.put("Orange", 35);
fruits.put("Lautturi", 32);
Map<String, Integer> sortedFruits = fruits.entrySet()
.stream()
// .sorted(Map.Entry.comparingByValue()) // sorting in natural/ascending order
// .sorted(Map.Entry.comparingByValue((o1, o2) -> Integer.compare(o1, o2))) // sorting in natural/ascending order
// .sorted(Map.Entry.comparingByValue((o1, o2) -> Integer.compare(o2, o1))) // sorting in reverse/descending order
// .sorted((x, y) -> x.getValue()-y.getValue()) // sorting in natural/ascending order
// .sorted((x, y) -> y.getValue()-x.getValue()) // sorting map/hashmap in reverse/descending order
// .sorted(Map.Entry.comparingByValue(Comparator.naturalOrder())) // sorting hashmap/map in natural/ascending order
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) // sorting map in reverse/descending order
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
System.out.println("original map:" + fruits);
System.out.println("sorted map:" + sortedFruits);
}
}Sow:ecruww.lautturi.comoutput:
original map:{Apple=21, Cherry=15, Lautturi=32, Orange=35, Banana=12}
sorted map:{Orange=35, Lautturi=32, Apple=21, Cherry=15, Banana=12}