helTech
helTech

Reputation: 95

Get element from list that contains another list

I have this configuration with java:

Student {
   private List<Note> notes;
}

Note {
   private int value;

   // Constructor - getters - setters
}

School {
   Private List<Student> students;

// Constructor - getters - setters
}

I want the following behavior:

Students :

S1 : note1(value=10), note2(value=16)

S2 : note1(value=7), note2(value=18), note3(value=2)

S3 : note1(value=19)

I want to manage an object with a list of schools as:

Manage {
   private List<School> schools;
}

And I want to get the school who has the student with the higher note.

In this example: the result would be S3 because we have one student with the higher note 19.

How can I achieve this behavior using Java Stream?

Upvotes: 0

Views: 66

Answers (1)

Eran
Eran

Reputation: 393801

You can create a Stream<Map.Entry<School,Student>> of all the pairs of Schools and Students, and then find the entry having the Student with the max value.

For that purpose I suggest adding to Student class a getMaxValue() method that would return the max value of all the Students Notes.

Optional<School> school =
    schools.stream()
           .flatMap(sc -> sc.getStudents()
                            .stream()
                            .map(st -> new SimpleEntry<>(sc,st)))
           .collect(Collectors.maxBy(Comparator.comparing(e -> e.getValue().getMaxValue())))
           .map(Map.Entry::getKey);

Upvotes: 1

Related Questions