Member-only story
How is takeWhile and dropWhile different from filter?
2 min readMay 15, 2024
In this tutorial, we will learn how takewhile and dropwhile different from filter. takeWhile and dropWhile are new additions to the Streams API introduced in Java 9. The takewhile() method of Stream API accepts all values until predicate returns false whereas dropWhile() method of Stream API drops all values until it matches the predicate.
package com.gain.java.knowledge;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamAPIMethods {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,9,8,7,6,5,4,3,2,1);
// Example 1: takeWhile
List<Integer> twLessThanFive = numbers.stream()
.takeWhile(n -> n < 5)
.collect(Collectors.toList());
System.out.println("Take While - Numbers less than 5: " + twLessThanFive);
// Example 2: dropWhile
List<Integer> dwGreaterThanFive = numbers.stream()
.dropWhile(n -> n <= 5)
.collect(Collectors.toList());
System.out.println("Drop While - Numbers greater than 5: " + dwGreaterThanFive);
// Example 3: filter
List<Integer> filterLessThanFive =
numbers.stream().filter(i -> i < 5 ).collect(Collectors.toList());
System.out.println("Filter - Numbers less than…