Stream anyMatch() 方法
方法语法
boolean anyMatch(Predicate<? super T> predicate)
这里的“predicate”是一个无干扰的、无状态的谓词,适用于流的元素。
如果至少一个元素满足由 predicate
提供的条件,则 anyMatch()
方法返回 true
,否则返回 false
。
说明
- 它是一种短路端子操作(short-circuiting terminal operation)。
- 它返回此流的任何元素是否与提供的谓词匹配。
- 如果不是确定结果所必需的,则可以不对所有元素评估谓词。一旦遇到第一个匹配元素,方法就会返回“true”。
- 如果流为空,则返回“false”并且不评估谓词。
- allMatch() 和 anyMatch() 之间的区别在于,如果流中的任何元素与给定的谓词匹配,则
anyMatch()
返回true
。使用allMatch()
时,所有元素都必须匹配给定的谓词。
Java Stream anyMatch(predicate) 是终端短路操作。
它用于检查流是否包含至少一个满足给定谓词的元素。
anyMatch() 和 contains() 的区别
理论上,当我们想要检查元素是否存在于 List
中时, anyMatch()
和 contains() 之间没有区别。
在某些情况下,并行性可能会为非常大的列表带来优势,但我们不应该每次都随意使用 Stream.parallel()
,并假设它可以使事情更快。
事实上,调用parallel()
可能会降低小流的性能。
查看更多教程 https://on itroad.com
Java Stream anyMatch() 示例
Java 检查流是否包含特定元素
使用 anyMatch()
方法来检查流是否包含字符串 `four""。
import java.util.stream.Stream; public class Main { public static void main(String[] args) { Stream<String> stream = Stream.of("one", "two", "three", "four"); boolean match = stream.anyMatch(s -> s.contains("four")); System.out.println(match); } }
带有多个谓词的 Stream anyMatch()
要满足多个条件,请使用两个或者多个简单谓词创建组合谓词。
检查流中是否包含年龄大于50或者薪水大于40000的元素
import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Stream; import lombok.AllArgsConstructor; import lombok.Data; public class Main { public static void main(String[] args) { Predicate<Employee> olderThan50 = e -> e.getAge() > 50; // 条件1 Predicate<Employee> earningMoreThan40K = e -> e.getSalary() > 40000; // 条件1 Predicate<Employee> combinedCondition = olderThan50.and(earningMoreThan40K); boolean result = getEmployeeStream().anyMatch(combinedCondition); System.out.println(result); } private static Stream<Employee> getEmployeeStream() { List<Employee> empList = new ArrayList<>(); empList.add(new Employee(1, "A", 46, 30000)); empList.add(new Employee(2, "B", 56, 30000)); empList.add(new Employee(3, "C", 42, 50000)); empList.add(new Employee(4, "D", 52, 50000)); empList.add(new Employee(5, "E", 32, 80000)); empList.add(new Employee(6, "F", 72, 80000)); return empList.stream(); } } @Data @AllArgsConstructor class Employee { private long id; private String name; private int age; private double salary; }
日期:2020-09-17 00:10:04 来源:oir作者:oir