首页 文章

Arrays.sort与Lambda然后比较

提问于
浏览
1

我是Java的新手,我正在尝试使用Lambda表达式和Comparators . 我有这个公共类Person与其他getter和toString方法:

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 []列表进行排序,首先按字符串(降序)进行比较,然后按年龄(升序)进行比较,然后按计算机数量(降序)进行比较,最后按薪资(升序)进行比较 . 我无法实现Comparable,因为如果我覆盖compareTo方法,它应该按升序或降序排列,我需要两者 . 我想知道是否可以在不创建自己的Comparator类的情况下这样做 . 基本上我的代码几乎是正确的,但我不知道如何反转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

提前谢谢大家!

1 回答

  • 6

    我想你只需要分别创建电脑 Comparator

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

相关问题