首页 > 解决方案 > 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?

标签: javastream

解决方案


您可以创建所有s 和sStream<Map.Entry<School,Student>>对中的 a ,然后找到具有最大值的条目。SchoolStudentStudent

为此,我建议向Student类添加一个方法,该方法将返回所有sgetMaxValue()的最大值。StudentNote

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);

推荐阅读