takeWhile keeps leading elements while a predicate holds; dropWhile skips them.
List<Integer> nums = List.of(1, 2, 3, 4, 1, 2);
System.out.println(nums.stream().takeWhile(n -> n < 4).toList());
System.out.println(nums.stream().dropWhile(n -> n < 4).toList());
[1, 2, 3]
[4, 1, 2]
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-26