Java Stream dropWhile() Method Tutorial

In this section, we will learn what the Stream dropWhile() method is and how to use it in Java.

What is Java Stream dropWhile() Method?

The Java Stream dropWhile() method is used to drop the elements of a stream as long as a set of conditions result true.

Basically, this method takes a reference to a method and passes every element in a stream as the argument to that method.

Now inside this reference method, we design a set of instructions that check every element in a stream to see if it matches the conditions. If yes, then that element will be dropped from the stream.

Now if and only if one element in the stream caused the conditions to result false, then the entire elements afterward will pass through the stream no-matter if they match the condition in the dropWhile() method or not.

For example, let’s say you have a condition that says as long as the elements are below the number 5 they should be dropped.

Now let’s say the stream has these values:

2,3,4,6,7,84,3,2,35,6,7,8,1,2,3,4,2,3

Here, the values (2,3,4) are matching the condition and so they will be dropped. But then the value 6 comes along and it doesn’t fit the condition! So it will pass.

From now on, even though we can see there are elements less than the value 5 in the stream, but they will pass as well because the condition in the dropWhile() method works as long as its result is true! But the moment it gets a value that negates the condition, the work of this method is done for the rest of elements in the stream.

Java dropWhile() Method Syntax:

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

dropWhile() Method Parameters:

The method takes one argument and that is of type Predicate, which is a functional interface.

Basically, this means we need to pass a reference of a method to this dropWhile() method.

The syntax of this reference method is:

  • It has one parameter which should be of the same type as the elements in the stream.
  • The return value of the method is a boolean.

Note: we can create this method using the lambda expression or refer to an instance or static method if there’s one in the program with the same signature.

dropWhile() Method Return Value:

The return value of this method is a new stream.

Example: using Stream dropWhile() method

import java.util.stream.Stream;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
        stream.dropWhile(e->e<5?true:false).forEach(e->System.out.print(e+", "));
    }
}

Output:

5, 6, 7, 8, 9,
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies