Learnitweb

Stream takeWhile method in Java

1. Introduction

The takewhile method was added in Stream interface in Java 9. takewhile is a default method in Stream interface.

Following is the signature of takewhile:

default Stream<T> takeWhile​(Predicate<? super T> predicate)

This method returns the stream of elements that matches the given predicate.

If this stream is ordered, it returns a stream comprising the longest sequence of elements from this stream that satisfy the provided predicate. If this stream is unordered, it returns a stream consisting of a subset of elements taken from this stream that match the given predicate.

If this stream is ordered then the longest prefix is a contiguous sequence of elements of this stream that match the given predicate.

In the case of an unordered stream where some elements meet the predicate but not all, the operation’s outcome becomes nondeterministic; it is free to take any subset of matching elements (which includes the empty set).

Regardless of the ordering of the stream, if all elements satisfy the predicate, the operation includes all elements (resulting in the same stream as the input). Conversely, if no elements match the predicate, the operation yields an empty stream.

2. Examples

2.1 Example 1

In the following example, l1 ArrayList is an ordered ArrayList. Predicate checks for the elements less than 5.

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class TakeWhileExample {
    public static void main(String[] args) {
        ArrayList<Integer> l1 = new ArrayList<Integer>();
        l1.add(1);
        l1.add(2);
        l1.add(3);
        l1.add(4);
        l1.add(5);
        l1.add(6);
        l1.add(7);
        l1.add(8);
        l1.add(9);
        l1.add(10);

        List<Integer> result = l1.stream().takeWhile(i -> i < 5).collect(Collectors.toList());
        System.out.println(result);
    }
}

Output

[1, 2, 3, 4]

2.2 Example 2

In the following example, l1 ArrayList is an unordered ArrayList. Predicate checks for the elements less than 5.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class TakeWhileExample {
    public static void main(String[] args) {
        ArrayList<Integer> l1 = new ArrayList<Integer>();
        l1.add(1);
        l1.add(3);
        l1.add(5);
        l1.add(7);
        l1.add(9);
        l1.add(8);
        l1.add(1);
        l1.add(3);
        l1.add(2);
        l1.add(6);

        List<Integer> result = l1.stream().takeWhile(i -> i < 6).collect(Collectors.toList());
        System.out.println(result);
    }
}

Output

[1, 3, 5]

3. Conclusion

Through this tutorial, we’ve delved into its syntax, functionality, and practical applications. By leveraging takeWhile(), developers can elegantly filter elements from streams based on specified conditions, improving code readability and performance.