Skip to main content

Posts

Java 8- Sorting a hashmap (by key and by value) using lambda expression and streams

Sometimes while working on business problems, it’s very common to come across use cases wherein a map needs to be sorted by either keys or by values. In this post, we will cover some of the examples to sort a map of primitives and custom objects.   In below approaches, we will not destroy existing map and will create a new map to ensure consistency of sorting 1. Sort HashMap by key  In order to sort a map by key, all we need to do is to use sorted method of stream interface and pass a default default/custom comparator to it. Moreover, to sort by keys, we need to use comparingByKey method of Entry interface of Map. 2. Sort HashMap by values  In order to sort a map by key, all we need to do is to use sorted method of stream interface and pass a default default/custom comparator to it. Moreover, to sort by keys, we need to use comparingByValue method of Entry interface of Map.

Java 8- Sorting Collections using lambda expression

Java 7 (old way)- 1. Create a comparator 2. Use Collections.sort or pass the comparator to constructor if you are using treeset or treemap 3. Use the comparator a)      Option 1- Pass comparator as argument- Collections.sort(collection, comparator); b)      Option 2- Keep collection sorted always TreeSet<Integer> treeset = new TreeSet<>(comparator); TreeMap<Integer, String> treemap = new TreeMap<>(comparator); Below are few examples- note this can be done only for collections which maintain the sorting order and at the time of initialization you don’t default sorting or order but some custom sorting order. Below is an example of one of the constructors which directly accepts a comparator Java 8- Using lambda expressions As comparator is a functional interface (consists of single abstract method), we can use lambda expression to c...