java8 查找方法(findAny) (findFirst), 匹配(anyMatch) (allMatch) (noneMatch)

本文介绍了Java8StreamAPI中的查找和匹配功能,包括anyMatch用于检查是否存在匹配元素,allMatch用于检查所有元素是否都匹配,noneMatch检查是否有不匹配元素,以及findAny和findFirst用于查找第一个元素。同时讨论了这些操作的短路性质和在并行流中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[Q&A] java8 短路操作
allMatchanyMatchnoneMatchfindFirstfindAnylimit

5.3.1 anyMatch:流中是否有一个元素能匹配给定的谓词

boolean anyMatch(Predicate<? super T> predicate);

// 菜单里面是否有素食可选择
if(menu.stream().anyMatch(Dish::isVegetarian)){
    System.out.println("The menu is (somewhat) vegetarian friendly!!");
}

5.3.2 allMatch:流中的元素是否能匹配给定的谓词

boolean allMatch(Predicate<? super T> predicate);

boolean isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000);

5.3.3 noneMatch:流中没有任何元素与给定的谓词匹配

boolean noneMatch(Predicate<? super T> predicate);

boolean isHealthy = menu.stream().noneMatch(d -> d.getCalories() >= 1000);

最佳实践:判断是否满足

---------------------------------------------
# 任意满足
List<Person> list = new ArrayList<>();
# 写法1
boolean present2 = list.stream().anyMatch(a -> a.getAge() > 10);
# 写法2 了解即可,无需记住
boolean present1 = list.stream().filter(a -> a.getAge() > 10).findAny().isPresent();
---------------------------------------------
# 全部满足
boolean present3 = list.stream().allMatch(a -> a.getAge() > 10);

Boolean high = true;
Boolean rich = true;
Boolean cool = true;
boolean b = Stream.of(high, rich, cool).allMatch(BooleanUtils::isTrue);
---------------------------------------------
# 全不满足
boolean present4 = list.stream().noneMatch(a -> a.getAge() > 10);

在这里插入图片描述

5.3.3 查找元素(findAny):返回当前流中的任意元素

Optional<T> findAny();

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

5.3.4 查找第一个元素(findFirst)

Optional<T> findFirst();

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

# 获取第一条数据
String str = list.stream().findFirst().orElse(null);

[Q&A] 为什么会同时有findFirstfindAny呢?
答案是 并行。找到第一个元素在并行上限制更多。如果你不关心返回的元素是哪个,请使用findAny,因为它在使用并行流时限制较少。

-----------------------------------------------------------------------------读书笔记摘自 书名:Java 8实战 作者:[英] Raoul-Gabriel Urma [意] Mario Fusco [英] Alan M

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值