java Stream takeWhile and java Stream dropWhile elements is part of Java 9 or letter version.

Java Stream takeWhile

it will not consider elements once predicate returns false. It used to discard ending elements from Stream.

If this stream is ordered then the longest prefix is a contiguous sequence of elements of this stream that match the given predicate. The first element of the sequence is the first element of this stream, and the element immediately following the last element of the sequence does not match the given predicate. If this stream is unordered, and some (but not all) elements of this stream match the given predicate, then the behavior of this operation is nondeterministic; it is free to take any subset of matching elements (which includes the empty set).

Java Stream takeWhile Example

Stream.of(1,3,5,6,8,6,2,18).takeWhile(no -> no<=5).forEach(System.out::println);

Output:

1
3
5

Java Stream dropWhile

It will start considering elements when predicate returns false. It used to discard starting elements of Stream.

If this stream is ordered then the longest prefix is a contiguous sequence of elements of this stream that match the given predicate. The first element of the sequence is the first element of this stream, and the element immediately following the last element of the sequence does not match the given predicate. If this stream is unordered, and some (but not all) elements of this stream match the given predicate, then the behavior of this operation is nondeterministic; it is free to drop any subset of matching elements (which includes the empty set).

Java Stream dropWhile Example

Stream.of(1,3,5,6,8,6,2,18).dropWhile(no -> no<=5).forEach(System.out::println);

Output:

6
8
6
2
18

 

 

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

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