WWW Baeldung Com Java 8 Sort Lambda - Comparator - Comparing
WWW Baeldung Com Java 8 Sort Lambda - Comparator - Comparing
by baeldung
Java +
Java 8
In this tutorial, we're going to take a 몭rst look at the Lambda support in Java
8 – speci몭cally at how to leverage it to write the Comparator and sort a
Collection.
This article is part of the “Java – Back to Basic” series here on Baeldung.
Further reading:
The Java 8 Stream API Tutorial
The article is an example-heavy introduction of the possibilities and
operations o몭ered by the Java 8 Stream API.
Read more →
Read more →
Read more →
new Comparator<Human>() {
@Override
public int compare(Human h1, Human h2) {
return h1.getName().compareTo(h2.getName());
}
}
@Test
public void
givenPreLambda_whenSortingEntitiesByName_thenCorrectlySorted() {
List<Human> humans = Lists.newArrayList(
new Human("Sarah", 10),
new Human("Jack", 12)
);
With the introduction of Lambdas, we can now bypass the anonymous inner
class and achieve the same result with simple, functional semantics:
@Test
public void whenSortingEntitiesByName_thenCorrectlySorted() {
List<Human> humans = Lists.newArrayList(
new Human("Sarah", 10),
new Human("Jack", 12)
);
humans.sort(
(Human h1, Human h2) -> h1.getName().compareTo(h2.getName()));
Notice that we're also using the new sort API added to java.util.List in Java
8 – instead of the old Collections.sort API.
We can further simplify the expression by not specifying the type de몭nitions
– the compiler is capable of inferring these on its own:
(h1, h2) -> h1.getName().compareTo(h2.getName())
@Test
public void
givenLambdaShortForm_whenSortingEntitiesByName_thenCorrectlySorted() {
Next, we're going to perform the sort using a Lambda Expression with a
reference to a static method.
First, we're going to de몭ne the method compareByNameThenAge – with the
exact same signature as the compare method in a Comparator<Human>
object:
Now, we're going to call the humans.sort method with this reference:
humans.sort(Human::compareByNameThenAge);
The end result is a working sorting of the collection using the static method
as a Comparator:
@Test
public void
givenMethodDefinition_whenSortingEntitiesByNameThenAge_thenCorrectlySort
ed() {
humans.sort(Human::compareByNameThenAge);
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
We can also avoid de몭ning even the comparison logic itself by using an
instance method reference and the Comparator.comparing method –
which extracts and creates a Comparable based on that function.
We're going to use the getter getName() to build the Lambda expression
and sort the list by name:
@Test
public void
givenInstanceMethod_whenSortingEntitiesByName_thenCorrectlySorted() {
List<Human> humans = Lists.newArrayList(
new Human("Sarah", 10),
new Human("Jack", 12)
);
Collections.sort(
humans, Comparator.comparing(Human::getName));
assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
7. Reverse Sort
JDK 8 has also introduced a helper method for reversing the comparator –
we can make quick use of that to reverse our sort:
@Test
public void whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
List<Human> humans = Lists.newArrayList(
new Human("Sarah", 10),
new Human("Jack", 12)
);
Comparator<Human> comparator
= (h1, h2) -> h1.getName().compareTo(h2.getName());
humans.sort(comparator.reversed());
The comparison lambda expressions need not be this simple – we can write
more complex expressions as well – for example sorting the entities 몭rst by
name, and then by age:
@Test
public void whenSortingEntitiesByNameThenAge_thenCorrectlySorted() {
List<Human> humans = Lists.newArrayList(
new Human("Sarah", 12),
new Human("Sarah", 10),
new Human("Zack", 12)
);
The same comparison logic – 몭rst sorting by name and then, secondarily, by
age – can also be implemented by the new composition support for
Comparator.
Starting with JDK 8, we can now chain together multiple comparators to
build more complex comparison logic:
@Test
public void
givenComposition_whenSortingEntitiesByNameThenAge_thenCorrectlySorted()
{
humans.sort(
Comparator.comparing(Human::getName).thenComparing(Human::getAge)
);
We can also sort a collection using Java 8's Stream sorted() API.
We can sort the stream using natural ordering as well as ordering provided
by a Comparator. For this, we have two overloaded variants of the sorted()
API:
@Test
public final void
givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted
() {
List<String> letters = Lists.newArrayList("B", "A", "C");
List<String> sortedLetters =
letters.stream().sorted().collect(Collectors.toList());
assertThat(sortedLetters.get(0), equalTo("A"));
}
Now let's see how we can use a custom Comparator with the sorted() API:
@Test
public final void
givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted(
){
List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new
Human("Jack", 12));
Comparator<Human> nameComparator = (h1, h2) ->
h1.getName().compareTo(h2.getName());
List<Human> sortedHumans =
humans.stream().sorted(nameComparator).collect(Collectors.toList());
assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
}
@Test
public final void
givenStreamComparatorOrdering_whenSortingEntitiesByName_thenCorrectlySor
ted() {
List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new
Human("Jack", 12));
@Test
public final void
givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrect
givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrect
lySorted() {
List<String> letters = Lists.newArrayList("B", "A", "C");
assertThat(reverseSortedLetters.get(0), equalTo("C"));
}
Now, let's see how we can use the sorted() method and a custom
Comparator:
@Test
public final void
givenStreamCustomOrdering_whenSortingEntitiesByNameReversed_thenCorrectl
ySorted() {
List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new
Human("Jack", 12));
Comparator<Human> reverseNameComparator =
(h1, h2) -> h2.getName().compareTo(h1.getName());
List<Human> reverseSortedHumans =
humans.stream().sorted(reverseNameComparator)
.collect(Collectors.toList());
assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah",
10)));
}
Note that the invocation of compareTo is 몭ipped, which is what is doing the
reversing.
Finally, let's simplify the above example by using the
Comparator.comparing() method:
@Test
public final void
givenStreamComparatorOrdering_whenSortingEntitiesByNameReversed_thenCorr
ectlySorted() {
List<Human> humans = Lists.newArrayList(new Human("Sarah", 10), new
Human("Jack", 12));
@Test(expected = NullPointerException.class)
public void givenANullElement_whenSortingEntitiesByName_thenThrowsNPE()
{
List<Human> humans = Lists.newArrayList(null, new Human("Jack",
12));
@Test
public void
givenANullElement_whenSortingEntitiesByNameManually_thenMovesTheNullToLa
st() {
List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12),
null);
humans.sort((h1, h2) -> {
if (h1 == null) {
return h2 == null ? 0 : 1;
}
else if (h2 == null) {
return -1;
}
return h1.getName().compareTo(h2.getName());
});
Assert.assertNotNull(humans.get(0));
Assert.assertNull(humans.get(1));
Assert.assertNull(humans.get(2));
}
@Test
public void
givenANullElement_whenSortingEntitiesByName_thenMovesTheNullToLast() {
List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12),
null);
humans.sort(Comparator.nullsLast(Comparator.comparing(Human::getName)));
Assert.assertNotNull(humans.get(0));
Assert.assertNull(humans.get(1));
Assert.assertNull(humans.get(2));
}
@Test
public void
givenANullElement_whenSortingEntitiesByName_thenMovesTheNullToStart() {
List<Human> humans = Lists.newArrayList(null, new Human("Jack", 12),
null);
humans.sort(Comparator.nullsFirst(Comparator.comparing(Human::getName)))
;
Assert.assertNull(humans.get(0));
Assert.assertNull(humans.get(1));
Assert.assertNotNull(humans.get(2));
}
13. Conclusion
This article illustrated the various and exciting ways that a List can be
sorted using Java 8 Lambda Expressions – moving right past syntactic
sugar and into real and powerful functional semantics.
The implementation of all these examples and code snippets can be found
over on GitHub.
12 COMMENTS Oldest
View Comments
SPRING
REST
JAVA
SECURITY
PERSISTENCE
JACKSON
HTTP CLIENT-SIDE
SERIES
ABOUT
ABOUT BAELDUNG
THE COURSES
JOBS
THE FULL ARCHIVE
WRITE FOR BAELDUNG
EDITORS
OUR PARTNERS
ADVERTISE ON BAELDUNG
TERMS OF SERVICE
PRIVACY POLICY
COMPANY INFO
CONTACT