Java 8 Lambda: Comparator Example

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

In this article, we will show you how to work with Java 8 Lambda expressions using the Comparator interface in Java.

1. Sort Without Lambda

Before Java 8 was released, we had to create an anonymous inner class for the Comparator to sort a collection.

Then we had to transfer the inner class and the collection to Collections.sort

Output:

2. Sort With Lambda

In Java 8, we use the Lambda expression instead of creating an anonymous inner class for the Comparator.

When we use the Lambda expression, the code is shorter.

By the way, you can shorten the code even more by leaving out the types for 01 and 02. If we don't include them, the code will look like this:

Example:

Output:

3. List.sort()

For Java 8, the sort() method was added to the List Interface. And as a result, instead of writing code like this:

we can now write code like this:

Example:

Output:

4. Reversed Sorting

With Java 8, reversed sorting has become much easier. You no longer have to make changes to already created Comparators.

Example:

Output:

5. More Lambda Examples

5.1 Sort By Name

Before Java 8:

Now:

Output:

5.2 Reversed Sort By Name

Before Java 8:

Now:

Note that the Comparator didn't change.

Output:

5.3 Sort By Using a Few Conditions

Before Java 8:

Now:

Output:

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr
Самоучители--узнать детальнее--