This method was added from Java 9.
1 |
default Stream<T> takeWhile(Predicate<? super T> predicate) |
The parameter of this method is the Predicate interface and this method takes the elements in your Stream object from left to right, until the condition of the Predicate object is no longer fulfilled.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.huongdanjava.javastream; import java.util.stream.Stream; public class Example { public static void main(String[] args) { Stream.of(1,2,3,4,5,6,7,8,9,10) .takeWhile(i -> i < 5) .forEach(System.out::println); } } |
In the above example, the condition for getting the elements from left to right is that they must be less than 5. When the element is greater than 5, the method will stop and returns the result.
Result: