0% found this document useful (0 votes)
5 views7 pages

6 Java Comparator Using Lambda

This document teaches how to use Java lambdas to create a concise comparator for sorting custom objects, specifically a list of Person class objects. It provides examples of sorting using both an anonymous class and a lambda expression, highlighting the advantages of the latter for brevity and clarity. The document includes code snippets for implementing the sorting functionality in a PersonService class.

Uploaded by

bhavishmatli
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views7 pages

6 Java Comparator Using Lambda

This document teaches how to use Java lambdas to create a concise comparator for sorting custom objects, specifically a list of Person class objects. It provides examples of sorting using both an anonymous class and a lambda expression, highlighting the advantages of the latter for brevity and clarity. The document includes code snippets for implementing the sorting functionality in a PersonService class.

Uploaded by

bhavishmatli
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Comparator Using Lambda

In this lesson, you will learn how to use the power of lambdas to write a concise comparator.

We'll cover the following

• Comparator example using anonymous class


• Comparator example using a lambda expression

If you’ve been working with Java for some time, then you’ve probably encountered
a scenario where you need to sort the elements in a collection.

If your collection contains a wrapper class object then the sorting is very easy.
Since all the wrapper classes implement the Comparable interface, you can directly
use [Link]() to sort your collection.

However, if your collection contains a custom class object then you need to
provide the logic to sort your object. In this lesson, we will look at an example in
which we will sort a list of Person class objects using a comparator. Then, we will
write a program to do the same task using lambdas.

Comparator example using anonymous class #


First, we will create a Person class.

public class Person {

private String name;


private int age;
private String country;

public Person(String name, int age, String country) {


[Link] = name;
[Link] = age;
[Link] = country;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}

public String getCountry() {


return country;
}
}

Now, we have a PersonService class. It has a getPersons(List<Person> persons)


method. It takes a list of person objects as input and returns a list of person object
in sorted order.

In this method, we are creating an anonymous comparator, which sorts the Person
objects on the basis of name.

import [Link];
import [Link];
import [Link];

public class PersonService {

public static List<Person> getPersons(List<Person> persons){


// Created an anonymous Comparator, which sorts the Person object on the basis of Person na
[Link](persons, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return [Link]().compareTo([Link]());
}
});
return persons;
}
}

Finally, we have a PersonMain class that runs our logic.

All code les are copied to end of the page...


[Link]

[Link]

[Link]

If you look at the Comparator interface, you notice that it is a functional interface.
It has only one abstract method called compare() . This makes it a perfect candidate
to be used in lambdas.

Comparator example using a lambda expression #


Now, let’s see how we can write the same logic using a lambda expression. As
discussed in the previous lesson, when writing lambdas, we only need to consider

the input parameters and the method body.

Below is the signature of the compare() method.

int compare(T o1, T o2)

It takes two parameters as input and returns an int.

Let’s start constructing the lambda expression:

The structure of lambda will be like:

(p1, p2) -> {};

Here, p1 and p2 are the two input parameters. We can name them anything.

Now, we will add the body.

(p1, p2) -> [Link]().compareTo([Link]());

So, this is the lambda expression for sorting the Person objects based on name.

You can see how easy and concise it is to write code with lambdas instead of using
anonymous classes.

All code les are copied to end of the page...


[Link]

[Link]

[Link]

In the next lesson, you will learn about the Predicate functional interface.

Code Files Content !!!


⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋⤋

-------------------------------------------------------------------------
| [Link] [1]
-------------------------------------------------------------------------

import [Link];
import [Link];

public class PersonMain {

public static void main(String args[]){


List persons = new ArrayList<>();
[Link](new Person("John" , 23 , "USA"));
[Link](new Person("Carl" , 23 , "Australia"));
[Link](new Person("Amit" , 23 , "India"));
[Link](new Person("Vikram" , 23 , "Bhutan"));
[Link](new Person("Kane" , 23 , "Brazil"));
// Calling getPerson() method which will return the List of Person in sorted order.
List sortedPersons = [Link](persons);

[Link]("Persons after sorting");


// Printing the name of each person.
for(Person person : sortedPersons){
[Link]("Person Name : " + [Link]());
}
}
}

-------------------------------------------------------------------------
| [Link] [1]
-------------------------------------------------------------------------

import [Link];
import [Link];
import [Link];

public class PersonService {

public static List getPersons(List persons){


[Link](persons, new Comparator() {
@Override
public int compare(Person p1, Person p2) {
return [Link]().compareTo([Link]());
}
});
return persons;
}
}
-------------------------------------------------------------------------
| [Link] [1]
-------------------------------------------------------------------------

public class Person {

private String name;


private int age;
private String country;

public Person(String name, int age, String country) {


[Link] = name;
[Link] = age;
[Link] = country;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}

public String getCountry() {


return country;
}
}

**********************************************************************************

-------------------------------------------------------------------------
| [Link] [2]
-------------------------------------------------------------------------

import [Link];
import [Link];
import [Link];

public class PersonService {

public static List getPersons(List persons) {


// Instead of creating an anonymous class, we have provided a lambda expression.
[Link](persons, (p1, p2) -> [Link]().compareTo([Link]()));
return persons;
}
}

-------------------------------------------------------------------------
| [Link] [2]
-------------------------------------------------------------------------

import [Link];
import [Link];

public class PersonMain {

public static void main(String args[]){


List persons = new ArrayList<>();
[Link](new Person("John" , 23 , "USA"));
[Link](new Person("Carl" , 23 , "Australia"));
[Link](new Person("Amit" , 23 , "India"));
[Link](new Person("Vikram" , 23 , "Bhutan"));
[Link](new Person("Kane" , 23 , "Brazil"));
// Calling getPerson() method which will return the List of Person in sorted order.
List sortedPersons = [Link](persons);

[Link]("Persons after sorting");


for(Person person : sortedPersons){
[Link]("Person Name : " + [Link]());
}
}
}

-------------------------------------------------------------------------
| [Link] [2]
-------------------------------------------------------------------------

public class Person {

private String name;


private int age;
private String country;

public Person(String name, int age, String country) {


[Link] = name;
[Link] = age;
[Link] = country;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}

public String getCountry() {


return country;
}
}

**********************************************************************************

You might also like