Skip to main content
Java 9 · Topic 4 of 6

Stream takeWhile and dropWhile

Definition​

takeWhile keeps items from the start of a stream until a condition first fails. dropWhile skips items from the start until the condition first fails and keeps the rest. Java 9 also added Stream.iterate with a stop condition.

Example code​

Cutting a stream at the first item that fails a test

import java.util.List;
import java.util.stream.Stream;

class Demo {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 10, 4, 5);

System.out.println(numbers.stream().takeWhile(n -> n < 5).toList()); // stops at 10
System.out.println(numbers.stream().dropWhile(n -> n < 5).toList()); // starts at 10

// iterate with a condition, like a for loop (Java 9)
System.out.println(Stream.iterate(1, n -> n <= 100, n -> n * 3).toList());
}
}

// Output:
// [1, 2, 3]
// [10, 4, 5]
// [1, 3, 9, 27, 81]

Finished this page? Track your progress (saved only in your browser).