Using Lambda Expression to sort a List in Java

Normally, before Java 8, when we want to sort a List object, we will use Comparator object.

For example:

Result:

Using Lambda Expression to sort a List in Java

Since Java 8, we have another way to do the sorting a List object. That is: using sort() method in List object with Lambda Expression.

Back to my example, I can re-write the code using sort() method and Lambda Expression as below:

The argument of sort() method is a Comparator interface and because Comparator interface has just only one method, then we can call it is Functional Interface and apply Lambda Expression for it.

When we run again the example, we will get the same result as above.

Using Lambda Expression to sort a List in Java

 

Add Comment