I am currently trying to learn streams in Java, however I stumbled upon a problem I couldn't solve on my own. Given a List of Person
objects with the attributes age, height and name. I want to write a method toString()
, that sorts the List by height and in case the heights are equal by age (everything in descending order). Is there a possibility to solve this with a stream? I know how to sort the List by height, however I don't understand how you would get the equal elements (Persons with the same height) and sort them as well by age.
Class Person
:
public class Person {
private int age;
private double height;
private String name;
public Person(int age, double height, String name){
this.age = age;
this.height = height;
this.name = name;
}
public int getAge() {
return age;
}
public double getHeight() {
return height;
}
public String getName() {
return name;
}
}
The Data class (where you create the toString method):
public class Data {
private List<Person> persons;
public Data(List<Person> persons){
this.persons = persons;
}
public String toString(){
//sort the list (persons) and return a String of names
return "";
}
}