Java 8 Stream - Why is filter method not executing? [duplicate]

烈酒焚心 提交于 2019-12-09 18:03:27

问题


I am learning filtering using java stream. But the stream after filtering is not printing anything. I think the filter method is not getting executed. My filtering code is as follows:

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

There is no compilation error and no exception also. Any suggestion?


回答1:


filter is an intermediate operation, which will be executed only if the Stream pipeline ends in a terminal operation.

For example :

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

As it is, your filter method is useless, since it always returns true, and thus performs no filtering.



来源:https://stackoverflow.com/questions/40862906/java-8-stream-why-is-filter-method-not-executing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!