2017-05-07 98 views
1

我是Java的新手,我尝试使用Lambda表达式和比较器进行练习。 我有这个公共类的人与其他getter和toString方法:Arrays.sort与Lambda然后比较

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(人:: 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

你为什么不定义'在Person类getters'? –

回答

4

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

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

谢谢!这工作:) – FollettoInvecchiatoJr