In this guide, you will learn about the Stream takeWhile() method in Java programming and how to use it with an example.
1. Stream takeWhile() Method Overview
Definition:
The takeWhile() method of the Stream interface in Java is used to return elements from the stream as long as the given predicate holds true. Once an element fails to match the predicate, the operation stops and the elements after that are not included in the resulting stream.
Syntax:
Stream<T> takeWhile(Predicate<? super T> predicate)
Parameters:
- predicate: A non-interfering, stateless predicate to apply to elements of the stream, which returns true if the element should be included in the result.
Key Points:
- Introduced in Java 9.
- This is a short-circuiting stateful intermediate operation.
- The operation stops as soon as the predicate returns false or the end of the stream is reached.
- If the stream is unordered, any subset of the elements satisfying the predicate may be returned.
- For ordered streams, the returned stream is also ordered.
2. Stream takeWhile() Method Example
import java.util.stream.Stream;
public class TakeWhileExample {
public static void main(String[] args) {
// Creating a Stream of integers
Stream<Integer> numberStream = Stream.of(2, 4, 6, 8, 9, 10, 12);
// Using takeWhile() to return elements as long as they are even
Stream<Integer> resultStream = numberStream.takeWhile(number -> number % 2 == 0);
// Displaying the result
resultStream.forEach(System.out::println);
}
}
Output:
2 4 6 8
Explanation:
In the example, we have a Stream of integers. We use the takeWhile() method to take elements from the stream as long as they are even. As soon as the method encounters the number 9, which is not even, the operation stops, and the remaining elements are not included in the resulting stream.
The output of the program demonstrates this, showing only the even numbers before the first odd number in the original stream.
Comments
Post a Comment
Leave Comment