How to sort an array of objects using the Comparator user interface in Java 8?

Custom Comparator Implementation

@FunctionalInterface
public interface Comparator<T>  {

int compare(T t1, T t2);

static <T> Comparator<T> comparing(
        Function<T, Comparable> f){
    return (p1, p2) -> f.apply(p1).compareTo(f.apply(p2));
}

default Comparator<T> thenComparing(
        Comparator<T> cmp){
            return (p1, p2) ->
                    this.compare(p1, p2) == 0 ?
                            cmp.compare(p1, p2) : this.compare(p1, p2);
}

default Comparator<T> thenComparing(
        Function<T, Comparable> f){
            Comparator<T> cmp = comparing(f);
    return thenComparing(cmp);
  }
}

I created a Person class with three fields, namely firstName, lastName and age, and their respective getters and seters. Using the custom Comparator class, I want to sort an array of faces in the main menu:

    Comparator<Person> cmp = Comparator
            .comparing(Person::getLastName) // Extract Property and compare
            .thenComparing(Person::getFirstName)
            .thenComparing(Person::getAge);

     Person arr[] = new Person[]{
        new Person("Sean", "Gilmore", 22),
                new Person("Aaron", "Reidy", 21),
                new Person("Jane", "Kennedy", 53),
                new Person("Mike", "English", 49)
    };


    Arrays.sort(arr, cmp);

However, it Arrays.sort(arr, cmp);produces a compilation errorno instance of type variable T exists so that Comparator<Person> conforms to Comparator<? super T>

I am throwing away this error and I would like to know how to sort the Person array using cmpComparator.

+4
source share
2 answers

You can easily adapt yours Comparatorto the JDK as follows:

Arrays.sort(arr, cmp::compare);

, Guava , Java 8.

+3

class Java .

Arrays.sort java.util.Comparator. Comparator , java.util.Comparator.

sort Arrays static, Arrays . Arrays.sort, java.util.Comparator. .

+3

Source: https://habr.com/ru/post/1669606/


All Articles