SoFunction
Updated on 2025-03-09

Lambda and sorting for Java8

Sort arrays and collections isJava 8 lambdaAn amazing application we can implement aComparatorsto implement various sorting.

See the following cases:

static class Person {

    final String firstName;

    final String lastName;

 
  
    Person(String firstName, String lastName) {

         = firstName;

         = lastName;

    }

 

    @Override

    public String toString() {

        return "Person{" +

                "firstName='" + firstName + '\'' +

                ", lastName='" + lastName + '\'' +

                '}';

    }

}

Person's data are:

List<Person> people =

(

    new Person("Jane", "Henderson"),

    new Person("Michael", "White"),

    new Person("Henry", "Brighton"),

    new Person("Hannah", "Plowman"),

    new Person("William", "Henderson")

);

We want to sort by name(last name), and then according to the last name (first name) sort.

Before Java 7, we usually implemented a Comparator:

(new Comparator<Person>() {

  @Override

  public int compare(Person o1, Person o2) {

    int result = ();

 

    if (result == 0)

      result = ();

 

    return result;

  }

});

(::println);

In Java 8, we can use lambda instead of anonymous functions, as follows:

Comparator<Person> c = (p, o) -> ();

 

c = ((p, o) -> ());

 

(c);

(::println);

Here,Lambdaexpression (p, o) -> ()Replace the previous anonymous functionnew Comparator<Person>() {}

becauseJavaThe compiler cannot delay theLambdaExpression type judgment, such as delay tocomparatorPass tosort()method, so we do chainingComparatorWriting is a bit difficult.

For example, we want to write it as follows:

 
((p, o) -> ())
       .thenComparing((p, o) -> ())

In other words, type judgment is from left to right, not from right to left, we can make type inference by creating a generic:

class Utils {

    static <E> Comparator<E> compare() {

        return (e1, e2) -> 0;

    }

}

Through the above compare() method, we can write a smooth comparator chain:

(

    Utils.<Person>compare()

         .thenComparing((p, o) ->

              ())

         .thenComparing((p, o) ->

              ())

);

 

(::println);

This is the end of this article about Java 8's Lambda and sorting. For more related Java Lambda and sorting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!