Arrays.sort 使用 Lambda 然后进行比较

Arrays.sort with Lambda and thenComparing

我是 Java 的新手,我正在尝试使用 Lambda 表达式和比较器。 我有这个 public class Person with other getters and toString method:

public class Person { 
    private String name;
    private int age;
    private int computers;
    private double salary;

public Person(String name, int age, int computers, double salary){
    this.name = name;
    this.age = age;
    this.computers = computers;
    this.salary = salary;
    }

public String getName(){
    return this.name;
}

public int getAge(){
    return this.age;
}

public int getComputers(){
    return this.computers;
}

public double getSalary(){
    return this.salary;
}
@Override
public String toString(){
    return "Name: " + getName() + ", age: "+ getAge() +
            ", N° pc: " + getComputers() + ", salary: " + getSalary();
}


}

现在我想对 Person[] 列表进行排序,首先按 String(降序)进行比较,然后按 Age(升序),然后按计算机数量(降序),最后按 Salary(升序) ).我无法实现 Comparable,因为如果我重写 compareTo 方法,它应该按升序或降序排列,而我两者都需要。我想知道是否可以在不创建自己的 Comparator classes 的情况下做到这一点。基本上我的代码几乎是正确的,但我不知道如何反转 thenComparingInt(Person::getComputers) ..

import java.util.Arrays;
import java.util.Comparator;


public class PersonMain {
   public static void main (String args[]){

    Person[] people = new Person[]{
            new Person("Adam",  30, 6, 1800),
            new Person("Adam",  30, 6, 1500),
            new Person("Erik",  25, 1, 1300),
            new Person("Erik",  25, 3, 2000),
            new Person("Flora", 18, 1, 800 ),
            new Person("Flora", 43, 2, 789),
            new Person("Flora", 24, 5, 1100),
            new Person("Mark",  58, 2, 2400)
    };

    Arrays.sort(people, Comparator.comparing(Person::getName).reversed()
            .thenComparingInt(Person::getAge)
            .thenComparingInt(Person::getComputers)
            .thenComparingDouble(Person::getSalary)
            );

    for (Person p: people)
        System.out.println(p);
  }
}

正确的输出应该是:

Name: Mark,  age: 58, N° pc: 2, salary: 2400.0
Name: Flora, age: 18, N° pc: 1, salary:  800.0
Name: Flora, age: 24, N° pc: 5, salary: 1100.0
Name: Flora, age: 43, N° pc: 2, salary:  789.0
Name: Erik,  age: 25, N° pc: 3, salary: 2000.0
Name: Erik,  age: 25, N° pc: 1, salary: 1300.0
Name: Adam,  age: 30, N° pc: 6, salary: 1500.0
Name: Adam,  age: 30, N° pc: 6, salary: 1800.0

先谢谢大家了!

我想你只需要单独创建计算机Comparator:

Comparator.comparing(Person::getName).reversed()
          .thenComparingInt(Person::getAge)
          .thenComparing(Comparator.comparingInt(Person::getComputers).reversed())
          .thenComparingDouble(Person::getSalary)