Java java microservices Java Virtual Machine
In this blog, we are going to take a look at the support that Lambda provides in Java 8, especially in terms of using it to write aComparator and sort a Collection.
Firstly, we define a simple class as follows:-
public class Person {
private String nameOfPerson;
private int ageOfPerson;
// standard constructors, getters/setters, equals and hashcode
}
The process of sorting a Collection, before Java 8, would involve creating an inner class for the comparator used in the class as :-
new Comparator<Person>() {
@Override
public int compare( Person h1, Person h2) {
return h1.getNameOfPerson().compareTo(h2.getNameOfPerson());
}
}
To sort the Person entities, the below code will be used.
Also, ReadPros and Cons of Updating a Project From Java 8 to Java 17
@Test
public void givenPreLambda_whenSortingEntitiesByNameOfPerson_thenCorrectlySorted() {
List<Person> persons = Lists.newArrayList(
new Person("Ankit", 15),
new Person("Rajesh", 20)
);
Collections.sort(persons, new Comparator<Person>() {
@Override
public int compare(Person h1, Person h2) {
return h1.getNameOfPerson().compareTo(h2.getNameOfPerson());
}
});
Assert.assertThat(persons .get(0), equalTo(new Person("Rajesh", 20)));
}
The introduction of Lambdas has enabled the developers to bypass the inner class and the best thing is that the same result is achieved.
(final Person h1, final Person h2) -> h1.getNameOfPerson().compareTo(h2.getNameOfPerson());
Accordingly, the behavior can be tested just as before:
@Test
public void whenSortingEntitiesByNameOfPerson_thenCorrectlySorted() {
List<Person> persons = Lists.newArrayList(
new Person("Ankit", 15),
new Person("Rajesh", 20)
);
persons.sort(
(Person h1, Person h2) -> h1.getNameOfPerson().compareTo(h2.getNameOfPerson()));
assertThat(persons.get(0), equalTo(new Person("Rajesh", 20)));
}
The important point that we should notice is that we are using the new sort API added to java.util.List in Java 8 in place of the Collections.sort API which has become old.
Also, ReadMulti Line String In Java
Further, we can also simplify the expression without specifying the definitions’ type. The compiler has that capacity of inferring the definitions by itself.
(h1, h2) -> h1.getNameOfPerson().compareTo(h2.getNameOfPerson())
Again, we can have the similar test as follows:
@Test
public void
givenLambdaShortForm_whenSortingEntitiesByNameOfPerson_thenCorrectlySorted() {
List<Person> persons = Lists.newArrayList(
new Person("Ankit", 15),
new Person("Rajesh", 20)
);
humans.sort((h1, h2) -> h1.getNameOfPerson().compareTo(h2.getNameOfPerson()));
assertThat(persons .get(0), equalTo(new Person("Rajest", 20)));
}