Reputation: 21
I'm new to Java and I'm trying to exercise with Lambda expressions and Comparators. I have this 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();
}
}
Now I would like to sort a Person[] list, comparing first by String (descending order), then by Age ( ascending order), then by number of computers (descending order) and finally by Salary ( ascending order). I cannot implements Comparable because if I override the compareTo method it should be in ascending or descend order and I need both. I would like to know if it's possible to do that without creating myself Comparator classes. Basically my code is almost correct but I don't know how to reverse the 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);
}
}
The correct output should be:
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
Thanks everyone in advance!
Upvotes: 1
Views: 2253
Reputation: 37875
I think you just need to create the computer Comparator
separately:
Comparator.comparing(Person::getName).reversed()
.thenComparingInt(Person::getAge)
.thenComparing(Comparator.comparingInt(Person::getComputers).reversed())
.thenComparingDouble(Person::getSalary)
Upvotes: 6