For example:
Given a Set<Set<Integer>>
, I have tried to use
int min = nestedSets.stream().map(s->s.stream().min(Comparator.naturalOrder()).get()).min(Comparator.naturalOrder()).get();
My initial idea was to use flatMap
, however it doesn't returns the desired result.
The returned type should be OptionalInt
since you don't know it the minimum value is found. You can do:
OptionalInt min = nestedSets.stream()
.flatMap(Set::stream)
.mapToInt(Integer::intValue)
.min();
Alternatively, you can use Comparator
with the very same mapping function (Integer::intValue
) inside Stream::min
which results in boxed Optional<Integer>
instead:
Optional<Integer> min = nestedSets.stream()
.flatMap(Set::stream)
.min(Comparator.comparingInt(Integer::intValue));
It depends if you need all these values or just either min
or max
.
Pros: I find these solutions easy to read, with no redundant code and the best way to compute min/max/avg or more.
Cons: You can compute only one value (either
min
ormax
) at the same time. UseIntSummaryStatistics
for summary computations otherwise as already answered here.