Stream 流之 match
一、方法概述
如果需要判断流中元素是否匹配指定的条件,可以使用 match 相关方法
allMatch : 所有元素是否都满足条件
noneMatch : 所有元素是否都不满足条件
anyMatch : 所有元素中是否有一个满足条件
二、案例
public class StreamDemo {
public static void main(String[] args) {
List<Person> personList = Arrays.asList(
new Person(1, "大毛", 30, 175),
new Person(2, "二毛", 25, 170),
new Person(3, "三毛", 26, 173),
new Person(4, "小毛", 30, 175));
// 获取 person 类型流
Stream<Person> personStream = personList.stream();
// 所有元素中是否全部满足条件(所有人的名字中是否都包含 "毛"
boolean flag1 = personStream.allMatch((item) -> item.getName().contains("毛"));
// 所有元素是否全部不满足条件(所有人的年龄是否都大于 30
boolean flag2 = personStream.noneMatch((item) -> item.getAge() > 30);
// 所有元素是否有一个满足条件(所有人的身高中是否有一个等于 173
boolean flag3 = personStream.anyMatch((item) -> Objects.equals(item.getHeight(), 173));
}
}

浙公网安备 33010602011771号