Bachiri Taoufiq Abderrahman Bachiri Taoufiq Abderrahman - 3 years ago 157
Java Question

Stream filter didn't work well I want to print 10 lines

Why doesn't this stream stop from printing

1
despite we have a filter?

Can someone explain it to me? This example is not accurate and the best example for manipulating streams, it's just for learning purposes.

Stream.generate(() -> "1")
.peek(System.out::println)
.filter(x -> x.length() > 1)
.limit(10)
.forEach(System.out::println);


The correct one is :

Stream.generate(() -> "1")
.limit(10)
.forEach(System.out::println);

Answer Source

Think of a stream as pipeline. Elements will keep coming out from the generate method. Each element is then passed through each subsequent operation.

So in your code:

Stream.generate(() -> "1")
            .peek(System.out::println)
            .filter(x -> x.length() > 1)
            .limit(10)
            .forEach(System.out::println);

The following keeps going:

  • A new "1" is generated
  • At peek, your "1" is printed
  • At filter, if "1"'s length is larger than 1, it will come through, otherwise it will be thrown away
  • If the "1" comes through the filter, it will reach limit. The limit only will let the first 10 elements through. After the 10th element, it will throw the element away

No elements will pass through the filter, because "1"'s length is never larger than 1. The limit never lets enough elements through and so the terminal operation is not reached, it never terminates.

That's why it keeps on repeating the first two lines.

I'll now explain why reversing the order of limit and filter works:

Stream.generate(() -> "1")
        .peek(System.out::println)
        .limit(10)
        .filter(x -> x.length() > 1)
        .forEach(System.out::println);

Only 10 elements will be printed first by peek then come through the limit bit. Then all those 10 elements does not come through the filter. But this time, the terminal operation is reached because filter is not like limit, which waits for 10 elements before carrying on. The whole thing terminates and no more elements is generated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download