Java, Software Development

Java 9 Stream filter, takeWhile, dropWhile methods

This post demonstrates how to use the new methods – takeWhile and dropWhile – of the Stream interface in Java 9 Jigsaw. We’ll touch briefly on Stream.filter(Predicate p) just to get comfortable before trying out the new methods.

Stream.filter(Predicate p)

The filter method still works the same way. Given a Stream of elements, it filters elements that match its predicate. Quite straightforward, isn’t it?

This outputs the following:

All matching elements are retained.

Stream.takeWhile(Predicate p)

The takeWhile method picks up each element that matches its predicate until it encounters an unmatching element. A portion of the stream – starting from that first encountered unmatching element up to the last element – is discarded.

Consider these codes:

The output is:

The first integer, 40, matches that predicate. The next value, 31, does not. Given the example values, the takeWhile method leaves the existing stream with only 40.

The method is similar to this implementation:

Stream.dropWhile(Predicate p)

The dropWhile method does the opposite of the takeWhile. If it finds the first element that does not match its predicate, it discards all items that came before that unmatching element.

The output is:

Here, the value 40 matches the predicate. When it processes 31 which does not match the predicate, dropWhile retains all the subsequent values starting from 31.

The method is similar to this implementation:

References

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like