Java Stream takeWhile() Method Tutorial

In this section we will learn what the Stream takeWhile() method is and how to use it in Java.

What is Java Stream takeWhile() Method?

The Java Stream takeWhile() method is used to take the elements of a stream as long as a set of conditions result true.

Basically, this method takes a reference to a method and passes every element in a stream as the argument to that method.

Now inside this reference method, we design a set of instructions that check every element in a stream to see if it matches the conditions. If yes, then that element will pass to the next step in the stream.

Now if and only if one element in the stream caused the conditions to result false, then the entire elements afterward will be dropped from the stream.

This means the work of the stream will be done after that.

For example, let’s say you have a condition that says as long as the elements in a stream are below the number 10 they can pass and move on to the next step in the stream.

Now let’s say the stream has these values:


Here, the values (2,3,4,6,7) are matching the condition and so they may pass. But then the value 84 comes along and it doesn’t fit the condition!

So at this stage, no-matter what element comes after the value 84, the entire elements will be dropped and essentially the work of the stream is done at this time.

Java takeWhile() Method Syntax:

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

takeWhile() Method Parameters:

The method takes one argument and that is of type Predicate, which is a functional interface.

Basically, this means we need to pass a reference of a method to this takeWhile() method.

The syntax of this reference method is:

  • It has one parameter which should be of the same type as the elements in the stream.
  • The return value of the method is a boolean.

Note: we can create this method using the lambda expression or refer to an instance or static method if there’s one in the program with the same signature.

takeWhile() Method Return Value:

The return value of this method is a new stream.

Example: using Stream takeWhile() method

class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
        stream.takeWhile(e->e<5?true:false).forEach(e->System.out.print(e+", "));


1, 2, 3, 4,

Top Technologies