2017-05-07 42 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