Streams: Simple Reductions in Java

Now that you have seen how to create and transform streams, we will finally get to the most important point—getting answers from the stream data. The methods covered in this section are called reductions. Reductions are terminal operations. They reduce the stream to a nonstream value that can be used in your program.

You have already seen a simple reduction: the count method that returns the number of elements of a stream.

Other simple reductions are max and min that return the largest or smallest value. There is a twist—these methods return an Optional<T> value that either wraps the answer or indicates that there is none (because the stream happened to be empty). In the olden days, it was common to return null in such a situ­ation. But that can lead to null pointer exceptions when it happens in an in­completely tested program. The Optional type is a better way of indicating a missing return value. We discuss the Optional type in detail in the next section. Here is how you can get the maximum of a stream:

Optional<String> largest = words.maxIString-compareToIgnoreCase);

System.out.println(“largest: ” + largest.orElse(“”));

The findFirst returns the first value in a nonempty collection. It is often useful when combined with filter. For example, here we find the first word that starts with the letter Q, if it exists:

Optional<String> startsWithQ

= words.filter(s -> s.startsWith(“Q”)).findFirst();

If you are OK with any match, not just the first one, use the findAny method. This is effective when you parallelize the stream, since the stream can report any match that it finds instead of being constrained to the first one.

Optionat<String> startsWithQ

= words.paratlel().fitter(s -> s.startsWith(“Q”)).findAny();

If you just want to know if there is a match, use anyMatch. That method takes a predicate argument, so you won’t need to use fitter.

boolean aWordStartsWithQ

= words.parallel().anyMatch(s -> s.startsWith(“Q”));

There are methods allMatch and noneMatch that return true if all or no elements match a predicate. These methods also benefit from being run in parallel.

Source: Horstmann Cay S. (2019), Core Java. Volume II – Advanced Features, Pearson; 11th edition.

Leave a Reply

Your email address will not be published. Required fields are marked *