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
.
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.
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.
default Stream<T> takeWhile(Predicate<? super T> predicate)
Predicate<? super T> predicate
: This is the predicate applied to the elements to find the longest prefix of elements.This method returns a stream.
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);}}
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 takeWhile
method on stringStream
with lengthPredicate
as the argument and store the result in filteredStream
.
Line 13: We use System.out.println
to print the value stored in filteredStream
.
The output contains [hello, educative]
because the predicate output for hi
in the stream is false
. Hence, the iteration stops there.