0

I have to get the list of objects containing the max value. The comparator max in Java 8 returns only one object.

To do this I had to stream twice the list:

 OptionalInt max = students.stream()
            .mapToInt(student -> student.getAssignedProjects().size())
            .max();

    return this.students.stream()
            .filter(student -> student.getAssignedProjects().size() == max.getAsInt())
            .collect(Collectors.toSet());

This solution works. I think there is a better way to solve this but I ca not figure it out.

1 Answers1

3

IF you want a single pipeline, you can group the Students by that property, and if you produce a TreeMap for the output, it will be sorted, so you'll have access to the Set corresponding with the max value:

return
this.students()
    .stream()
    .collect(Collectors.groupingBy(student -> student.getAssignedProjects().size(),
             TreeMap::new,
             Collectors.toSet()))
    .lastEntry()
    .getValue();

Of course, if the number of Students having the max value is small relative to the size of the input list, it would be inefficient to sort the grouped Students (which is what creating a TreeMap would do). Your original code would be more efficient.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Any chance to use `Collectors.maxBy` here? I tried to find a different *single pipeline* without success so far. – deHaar Nov 26 '19 at 10:17
  • @deHaar I believe `maxBy` would return a single element (having the max value), so it doesn't fit the OP's requirements. – Eran Nov 26 '19 at 10:19
  • I know, that's why I didn't succeed using it... It cannot be used along with `Collectors.toList()` or similar. I thought there might be a way... – deHaar Nov 26 '19 at 10:20