Use Lambda Expression to sort elements of a List in Java

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

Eg:

Result:

Use Lambda Expression to sort elements of a List in Java

From Java 8 onwards, we have another way of doing this. That is, using the sort() method of the List object with the Lambda Expression.

Now we can rewrite the above example with the sort() method and Lambda Expression:

The parameter of the sort() method is a Comparator interface. Comparator interface is a Functional Interface so we can use Lambda Expression for it.

The result is the same:

Use Lambda Expression to sort elements of a List in Java

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment