How to get the min/max element of nested collections without redundant code using streams?

Jesús Díaz Castro :

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.

Nikolas :

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 or max) at the same time. Use IntSummaryStatistics for summary computations otherwise as already answered here.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=477532&siteId=1