-2

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 "";
    }
}
Silent Tree
  • 987
  • 1
  • 7
  • 16

1 Answers1

6

You can use Comparator chaining to sort by height and then by age. Then use the map operator to map the names and finally joining collector to concatenate the names into a formatted string of your interest. Here's how it looks.

String sortedNames = persons.stream()
    .sorted(Comparator.comparingDouble(Person::getHeight)
        .thenComparingDouble(Person::getAge).reversed())
    .map(Person::getName)
    .collect(Collectors.joining(", "));

P.S. However, I don't see double as a good data type to represent the age of a person. An int would be a much better alternative IMO.

Update:

If you have int data type to represent the age of a person, then the comparator chain should look like below. Everything else remains intact.

Comparator.comparingDouble(Person::getHeight)
        .thenComparingInt(Person::getAge).reversed()
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63