0

Can someone please explain the output of below java streams code:

List<Integer> l = new ArrayList<>();
l.add(0);
l.add(1);
l.add(2);
l.add(3);
l.add(4);
l.add(4);
l.stream()
    .distinct()
    .map(v -> {
        System.out.println("In Map " + v);
        return v;
    }).forEach(v -> {
        System.out.println("In ForEach " + v);
    });

I expected:

In Map 0 
    In Map 1 
    In Map 2 
    In Map 3 
    In Map 4 
    In ForEach 0 
    In ForEach 1 
    In ForEach 2 
    In ForEach 3 
    In ForEach 4

But it prints:

In Map 0 
    In ForEach 0 
    In Map 1 
    In ForEach 1 
    In Map 2 
    In ForEach 2 
    In Map 3 
    In ForEach 3 
    In Map 4 
    In ForEach 4
hunteke
  • 3,648
  • 1
  • 7
  • 17
Arun Kumar V
  • 309
  • 3
  • 4
  • 11

2 Answers2

0

I think it is pretty obvious :) It goes in Map and for each value does the foreach call. It's like nested loops. Get value 1 - process it, get value 2 process it ;) And that's what you get

Veselin Davidov
  • 7,031
  • 1
  • 15
  • 23
0

The Stream pipeline is lazily evaluated. Meaning it performs intermediate operations on Stream elements only when such elements are required by the terminal operation - forEach in your case.

If the terminal operation required only a single element (for example findFirst()), the map() operation would be executed only for the first element of the Stream.

Eran
  • 387,369
  • 54
  • 702
  • 768