The dropWhile()
method of the Stream
interface is used to return drop the longest prefix of elements that satisfy the given predicate while returning the remaining elements of the stream.
Refer What is a Java predicate? to learn more about predicate.
default Stream<T> dropWhile(Predicate<? super T> predicate)
Predicate<? super T> predicate
: This is the predicate that should be applied to elements in order 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.dropWhile(lengthPredicate).collect(Collectors.toList());System.out.println("dropWhile output - " + filteredStream);}}
stringStream
.lengthPredicate
checks whether the length of a given string is greater than or equal to 5.dropWhile
method is applied on stringStream
with lengthPredicate
as the argument.The output contains only [hi, edpresso]
because the predicate matches the first two elements of the stream and hence is dropped. The method returns the remaining elements.