What is the Stream.dropWhile method in Java?

Overview

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.

  • The longest prefix is a continuous series of elements in the stream that satisfies the specified predicate if the stream is ordered.
  • 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 drop any subset of matching elements.

Refer What is a Java predicate? to learn more about predicate.

Syntax


default Stream<T> dropWhile(Predicate<? super T> predicate)

Parameters

  • Predicate<? super T> predicate: This is the predicate that should be applied to elements in order to find the longest prefix of elements.

Return value

This method returns a stream.

Code

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);
}
}

Explanation

  • Lines 1-4: Relevant classes and packages are imported.
  • Line 10: We define a stream of strings called stringStream.
  • Line 11: A predicate called lengthPredicate checks whether the length of a given string is greater than or equal to 5.
  • Line 12: The dropWhile method is applied on stringStream with lengthPredicate as the argument.
  • Line 13: The output is printed.

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.

Free Resources