Java Lambda Expression with Collections
In this article, Lambda Expression with Collections is discussed with examples of sorting different collections like ArrayList, TreeSet, TreeMap, etc. Sorting Collections with Comparator (or without Lambda): We can use Comparator interface to sort, It only contains one abstract method: – compare(). An interface that only contains only a single abstract method then it is called a Functional Interface.
- Use of Comparator(I): –
- Prototype of compare() method: –
While defining our own sorting, JVM is always going to call Comparator to compare() method.
- returns negative value(-1), if and only if obj1 has to come before obj2.
- returns positive value(+1), if and only if obj1 has to come after obj2.
- returns zero(0), if and only if obj1 and obj2 are equal.
In List, Set, Map, or anywhere else when we want to define our own sorting method, JVM will always call compare() method internally. When there is Functional Interface concept used, then we can use Lambda Expression in its place. Sorting elements of List(I) with Lambda
Expression: – Using lambda expression in place of comparator object for defining our own sorting in collections.
Sorting TreeSet using Lambda Expression:
Sorting elements of TreeMap using Lambda Expression: Sorting will be done on the basis of the keys and not its value.
It is also possible to specify a reverse comparator via a lambda expression directly in the call to the TreeSet() constructor, as shown here:
G F E D C B A