与过滤器有何不同? [英] How is takeWhile different from filter?

查看:89
本文介绍了与过滤器有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

takeWhile()与Java 9中的filter()有何不同?

How is takeWhile() different from filter() in Java 9. What extra utility does it have?

Stream.of(1,2,3,4,5,6,7,8,9,10).filter(i -> i < 4 )
        .forEach(System.out::println);

这也许是下面的人会做的

This is perhaps what following would do

Stream.of(1,2,3,4,5,6,7,8,9,10).takeWhile(i -> i < 4 )
        .forEach(System.out::println);

那么这个新功能有什么需要?

What was the need of this new function then?

推荐答案

过滤器将从流中删除所有不满足条件的项目.

filter will remove all items from the stream that do not satisfy the condition.

takeWhile 将在第一次出现不符合条件的项目时中止流.

takeWhile will abort the stream on the first occurrence of an item which does not satisfy the condition.

例如

Stream.of(1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1)
    .filter(i -> i < 4 )
    .forEach(System.out::print);

将打印

123321

123321

但是

Stream.of(1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1)
    .takeWhile(i -> i < 4 )
    .forEach(System.out::print);

将打印

123

这篇关于与过滤器有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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