on it road.com
Stream allMatch() 示例
检查所有流元素是否不包含任何数字字符
下面示例中,如果流中的任何字符串都不包含任何数字字符。allMatch()返回 true。
import java.util.function.Predicate;
import java.util.stream.Stream;
public class Main
{
public static void main(String[] args)
{
Stream<String> stream = Stream.of("one", "two", "three", "four");
Predicate<String> containsDoirt = s -> s.contains("\d+") == false;
boolean match = stream.allMatch(containsDoirt);
System.out.println(match);
}
}
输出:
true
包含多个条件的 Stream.allMatch()
要满足多个条件,请使用两个或者多个简单谓词创建组合谓词。
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() > 40_000; // 条件2
Predicate<Employee> combinedCondition = olderThan50.and(earningMoreThan40K);
boolean result = getEmployeeStream().allMatch(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;
}
输出:
false
Stream allMatch() 方法
语法
boolean allMatch(Predicate<? super T> predicate)
这里的“Predicate ”是一个无干扰的、无状态的谓词,适用于流的所有元素。
allMatch()方法根据评估结果始终返回 true或者 false。
说明
- 它是短路端子操作。
- 它返回此流的所有元素是否与提供的
predicate匹配。 - 如果不是确定结果所必需的,则可以不对所有元素评估“谓词”。如果所有流元素都匹配给定的谓词,则方法返回
true,否则方法返回false。 - 如果流为空,则返回
true并且不评估谓词。 - allMatch() 和 anyMatch() 之间的区别在于,如果流中的任何元素与给定的谓词匹配,则
anyMatch()返回true。使用allMatch()时,所有元素都必须匹配给定的谓词。
Java Stream allMatch(predicate)是一个短路终端操作,用于检查流中的所有元素是否满足提供的谓词。
日期:2020-09-17 00:10:06 来源:oir作者:oir
