The sum(), min(), and max() terminal operations

Now, let's combine the elements of this stream to express the following queries:

  • How can we calculate the total weight of melons (sum())?
  • What is the heaviest melon (max())?
  • What is the lightest melon (min())?

In order to calculate the total weight of melons, we need to sum up all the weights. For primitive specializations of Stream (IntStream, LongStream, and so on), the Java Stream API exposes a terminal operation named sum(). As its name suggests, this method sums up the elements of the stream:

int total = melons.stream()
.mapToInt(Melon::getWeight)
.sum();

After sum(), we also have the max() and min() terminal operations. Obviously, max() returns the maximum value of the stream, while min() is its opposite:

int max = melons.stream()
.mapToInt(Melon::getWeight)
.max()
.orElse(-1);

int min = melons.stream()
.mapToInt(Melon::getWeight)
.min()
.orElse(-1);
The max() and min() operations return an OptionalInt (such as OptionalLong). If the maximum or minimum cannot be calculated (for example, in the case of an empty stream) then we choose to return -1. Since we are working with weights, and with positive numbers by their nature, returning -1 makes sense. But don't take this as a rule. Depending on the case, another value should be returned, or maybe using orElseGet()/orElseThrow() would be better.

For non-primitive specializations, check out the Summarization collectors section of this chapter.

Let's learn about reducing in the next section.

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

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