0

Is it possible (or even viable) to merge these two stream operations into a single pass solution?

int max = locations.stream()
        .map(location -> location.getAvailableScooters().size())
        .max(Comparator.naturalOrder())
        .orElse(-1);

return locations.stream()
        .filter(location -> location.getAvailableScooters().size() == max)
        .collect(Collectors.toSet());
Naman
  • 27,789
  • 26
  • 218
  • 353
Richard Avalos
  • 555
  • 5
  • 18
  • Since `max` accepts a Comparator, you could have rather look into creating a `Comparator` to find the `max`, having said that you are looking for all the elements matching the criteria and `groupingBy` with `maxBy` could be of help here. – Naman Nov 29 '20 at 15:39

1 Answers1

0

The only way I see the merging is possible is like this:

return locations.stream()
        .filter(location -> location.getAvailableScooters().size() == 
                 locations.stream()
                .map(location -> location.getAvailableScooters().size())
                .max(Comparator.naturalOrder())
                .orElse(-1) )
        .collect(Collectors.toSet());

which is a much worse solution
max and collect are both terminal operations which makes the merging impossible

VFX
  • 496
  • 4
  • 13