Pages

Saturday, June 9, 2018

Java 8 sorting examples

How many lines of code did you write to sort a collection of objects before Java 8 ? How many, you will need with Java 8 ?
You can do it with a single line in Java 8.

Let's see the following Employee class.

public class Employee {
 
     private String name;
 
     private Integer age;
 
     public Employee(String name, Integer age) {
         super();
         this.name = name;
         this.age = age;
     }

     public String getName() {
         return name;
     }

     public void setName(String name) {
         this.name = name;
     }

     public Integer getAge() {
         return age;
     }

     public void setAge(Integer age) {
        this.age = age;
     }

}

Using the Collection's sort() method, employee list can be sorted. The sort() method expects a Comparator as an argument in order to compare two Employee objects. So our first solution looks like as follows.


public class EmployeeComparotor implements Comparator {
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.getAge().compareTo(e2.getAge()); 
    }
}

employeeList.sort(new EmployeeComparotor());

Rather than implementing Comparator and instantiating a new instance of it, we can use an anonymous class to improve our program.

employeeList.sort(new Comparator() {
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.getAge().compareTo(e2.getAge()); 
    }
}); 

Now, let's see, how can we improve this code further in order to reduce the verbosity by using Java 8 features. Java 8 introduces lambda expressions which allows us to pass a code to a method. Lambda expression can be passed to a method where functional interface is expected. A functional interface is an interface defining only one abstract method. In Java 8, the Comparator is a functional interface. The Collection's sort() method expects a Comparator as an argument, which accepts a functional interface. In this case, the Comparator represents BiFunction's descriptor. The BiFunction is a functional interface in Java 8. So then, you can pass a lambda expression into the sort method as follows. In order to sort employee list by their age, you need a single line as follows.

employeeList.sort((Employee e1, Employee e2) -> e1.getAge().compareTo(e2.getAge()));

Java compiler can infer the types of parameters of a lambda expression by using the context in which the lambda appears. So you can remove the types of parameter and rewrite the code as follows.

employeeList.sort((e1, e2) -> e1.getAge().compareTo(e2.getAge()));

Let's try to further reduce the code. Java 8 Comparator has a static method called comparing() that accepts a Function as an argument. This Function should extract the sort key and produce a Comparator object. So the shortest code to sort a list of objects in Java 8 will be,

employeeList.sort(comparing((e) -> e1.getAge()));

In stead of using a lambda expression, we can use method references to make our code slightly less verbose.

employeeList.sort(comparing(Employee::getAge));

If you want to sort the employee list by descending order in age, you can use the reversed() default method of the interface.

employeeList.sort(comparing(Employee::getAge).reversed());

Now, let's see, you want to sort the employees in their age and then, similar age employees by their names. Just remind, how did you do this earlier version of Java. In Java 8, you can simply use thenComparing() method in order to do this.

employeeList.sort(comparing(Employee::getAge).thenComparing(Employee::getName));



1 comments:

Share

Widgets