Stream的查找与匹配

Stream流中的某些元素是否匹配一个给定的属性。Stream API通过allMatch、anyMatch、noneMatch、findFirst和findAny方法提供了这样的工具。

anyMatch:流中是否有一个元素能满足给定的条件,是返回true否则false。


String[] words = {"Goodbye", "World"};
boolean falg=worlds.stream().anyMatch(w->w.length>6);

allMatch:流中所有元素能满足给定的条件,是返回true否则false。


String[] words = {"Goodbye", "World"};
boolean falg=worlds.stream().allMatch(w->w.length>4);

noneMatch:流中所有元素能不满足给定的条件,是返回true否则false。


String[] words = {"Goodbye", "World"};
boolean falg=worlds.stream().allMatch(w->w.length>10);

短路求值:类似于java中的||、&&。在对一个流进行处理的时候,条件用and连接起来,只要一个条件不满足为false,则整体返回为false。这就是短路。

findAny:方法将返回当前流中的任意元素。它可以与其他流操作结合使用。

查找菜单中是否有素食可以选择。注意:Optional类(java.util.Optional)是一个容器类,代表一个值存在或不存在。isPresent()将在Optional包含值的时候返回true,否则返回false。后续再做详细的介绍。


Optional<Dish> dish=menu.stream().filter(Dish::isVegetarian).findAny();

findFirst:找到流中满足给定条件的第一个元素。


List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> firstSquareDivisibleByThree =nums .stream().filter(x -> x % 2 == 0).findFirst(); // 2

 

版权声明:
作者:Gomo
链接:https://www.develophm.com/index.php/stream%e7%9a%84%e6%9f%a5%e6%89%be%e4%b8%8e%e5%8c%b9%e9%85%8d/426/
来源:开发之家
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>