Java 8 stream – why is the filter method not executed?

See English answers > why does java8 stream generate nothing? 3

Stream.of("d2","a2","b1","b3","c")
    .filter(s -> {
        s.startsWith("b");
        System.out.println("filter: " + s);
        return true;
    });

There are no compilation errors and no exceptions Any suggestions?

Solution

Filter is an intermediate operation that is executed only when the stream pipeline ends in a terminal operation

For example:

Stream.of("d2","c")
  .filter(s -> {
        s.startsWith("b");
        System.out.println("filter: " + s);
        return true;
  })
  .forEach (System.out::println);

In fact, your filtering method is useless because it always returns true, so it does not perform filtering

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>