Java-Stream - map() operation doesn't produce expected output

Viewed 47

My code:

import java.util.*;

class HelloWorld {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(3, 6, 9, 12, 15);
        list.stream().map(i -> convert(i));
        convert(1);
    }
    
    public static int convert (int i) {
        System.out.println(i);
        return i + 1;
    }
}

It outputs:

1

I was thinking it would output:

3
6
9
12
15
1

Could someone explain why it happened? is it because stream is stateless?

2 Answers

You always need a terminal operation (e.g. forEach(), reduce(), collect(), findFirst(), anyMatch(), etc.), which produces a value or a final action, to galvanize a stream into action as @rgettman has pointed out in the comments.

Streams are lazy, and operations in the stream pipeline get executed only if needed. Streams don't act like loops. If you don't need to produce a result from the stream, there's no reason for it to be executed. Sometimes it might be handy, you can create a stream and then hand it out to another method where it would be processed.

Note, that map() - is an intermediate operation, it produces another stream (not a result).

Here's a quote from the documentation

Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.

No, it's because it's never executed. Java streams require a final terminating operation, such as collect to run. In your case you could also use forEach instead of map since you are not using the return value of convert.

Related