What is the Stream.takeWhile method in Java?
Overview
The takeWhile() method of the Stream interface returns the elements as long as the given predicate is true. This means it returns the longest prefix of elements that match the given predicate. The iteration stops once the predicate becomes false. This means the element in the stream after the last return value is the element for which the predicate returns false.
Longest prefix
The longest prefix is a continuous series of elements in the stream that satisfies the specified predicate if the stream is ordered. The stream’s first element is the first element of the sequence. The element immediately following the last element of the sequence does not match the given predicate.
Nondeterministic execution
The method execution is nondeterministic if this stream is unordered and some of the elements in the stream satisfy the supplied predicate. The method can take any subset of matching elements that includes the empty set.
Syntax
default Stream<T> takeWhile(Predicate<? super T> predicate)
Parameters
Predicate<? super T> predicate: This is the predicate applied to the elements to find the longest prefix of elements.
Return value
This method returns a stream.
Example
import java.util.List;import java.util.function.Predicate;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {public static void main(String[] args){Stream<String> stringStream = Stream.of("hello", "educative", "hi", "edpresso");Predicate<String> lengthPredicate = string -> string.length() >= 5;List<String> filteredStream = stringStream.takeWhile(lengthPredicate).collect(Collectors.toList());System.out.println("takeWhile output - " + filteredStream);}}
Explanation
-
Lines 1–4: We import the relevant classes and packages.
-
Line 10: We define a stream of strings called
stringStream. -
Line 11: We define a predicate,
lengthPredicate. This checks whether the length of a given string is greater than or equal to 5. -
Line 12: We apply the
takeWhilemethod onstringStreamwithlengthPredicateas the argument and store the result infilteredStream. -
Line 13: We use
System.out.printlnto print the value stored infilteredStream.
Output
The output contains [hello, educative] because the predicate output for hi in the stream is false. Hence, the iteration stops there.