Maximum and minimum

In the Sum, max, and min in a stream section, we already computed the minimum and maximum value via the min() and max() methods. This time, let's compute the heaviest and the lightest Melon via the Collectors.maxBy() and Collectors.minBy() collectors. These collectors take a Comparator as an argument to compare the elements in the stream and return an Optional (this Optional will be empty if the stream is empty):

Comparator<Melon> byWeight = Comparator.comparing(Melon::getWeight);

Melon heaviestMelon = melons.stream()
.collect(Collectors.maxBy(byWeight))
.orElseThrow();

Melon lightestMelon = melons.stream()
.collect(Collectors.minBy(byWeight))
.orElseThrow();

In this case, if the stream is empty, we just throw NoSuchElementException.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.227.82