Unlike filter, these Java 9 operations stop at the first element that fails the predicate, so the order of the data matters.
var nums = List.of(1, 2, 3, 10, 4, 5);
System.out.println("takeWhile(n < 5) = " + nums.stream().takeWhile(n -> n < 5).toList());
System.out.println("dropWhile(n < 5) = " + nums.stream().dropWhile(n -> n < 5).toList());
System.out.println("filter(n < 5) = " + nums.stream().filter(n -> n < 5).toList());
takeWhile(n < 5) = [1, 2, 3]
dropWhile(n < 5) = [10, 4, 5]
filter(n < 5) = [1, 2, 3, 4]
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30