Java Stream dropWhile()

In this guide, you will learn about the Stream dropWhile() method in Java programming and how to use it with an example.

1. Stream dropWhile() Method Overview

Definition:

The dropWhile() method of the Stream interface in Java is used to discard elements from the stream as long as the given predicate holds true. Once an element fails to match the predicate, the operation stops, and the elements after that are included in the resulting stream.

Syntax:

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

Parameters:

- predicate: A non-interfering, stateless predicate to apply to elements of the stream, which returns true if the element should be discarded.

Key Points:

- Introduced in Java 9.

- This is a stateful intermediate operation.

- For ordered streams, it drops the longest prefix of elements that match the predicate.

- If the stream is unordered, some (or none) elements will be dropped until the predicate returns false.

2. Stream dropWhile() Method Example

import java.util.stream.Stream;

public class DropWhileExample {
    public static void main(String[] args) {
        // Creating a Stream of integers
        Stream<Integer> numberStream = Stream.of(2, 4, 6, 8, 9, 10, 12);

        // Using dropWhile() to discard elements as long as they are even
        Stream<Integer> resultStream = numberStream.dropWhile(number -> number % 2 == 0);

        // Displaying the result
        resultStream.forEach(System.out::println);
    }
}

Output:

9
10
12

Explanation:

In the example, we have a Stream of integers. We use the dropWhile() method to discard elements from the stream as long as they are even. 

As soon as the method encounters the number 9, which is not even, the operation stops, and the remaining elements are included in the resulting stream. 

The output of the program demonstrates this, showing the numbers in the original stream that appear after the first odd number.

Comments