Java 8 Stream - 为什么filter方法不能执行? [英] Java 8 Stream - Why is filter method not executing?

查看:2215
本文介绍了Java 8 Stream - 为什么filter方法不能执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习使用java流过滤。
但过滤后的流不打印任何东西。
我认为过滤方法没有得到执行。
我的过滤代码如下所示:

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

没有编译错误也没有例外。
任何建议?

解决方案

是一个中间操作,只有流管道在终端操作结束时才会执行。



例如:

<$ p $ Stream.of(d2,a2,b1,b3,c)
.filter(s - > {
s。 (b);
System.out.println(filter:+ s);
return true;
})
.forEach(System.out ::的println);

实际上,你的过滤方法是无用的,因为它总是返回 true ,因此不执行过滤。


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?

解决方案

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.

这篇关于Java 8 Stream - 为什么filter方法不能执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆