首页 / JAVA / 应用OR谓词Java 8
应用OR谓词Java 8
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了应用OR谓词Java 8,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2432字,纯文字阅读大概需要4分钟。
内容图文
![应用OR谓词Java 8](/upload/InfoBanner/zyjiaocheng/757/4d76afbd4bf44c35b6ba873b7a105cbc.jpg)
我有员工对象
public class Employee {
public Employee(Integer id, Integer age, String gender, String fName, String lName) {
this.id = id;
this.age = age;
this.gender = gender;
this.firstName = fName;
this.lastName = lName;
}
private Integer id;
private Integer age;
private String gender;
private String firstName;
private String lastName;
我有两个谓词
public static Predicate<Employee> firstNameLike(final String name) {
return p -> p.getFirstName().contains(name);
}
public static Predicate<Employee> isAdultFemale() {
return p -> p.getAge() > 18 && p.getGender().equalsIgnoreCase("F");
}
我正在向员工应用多个过滤器,例如
public class TestEmployeePredicates {
public static void main(String[] args) {
Employee e2 = new Employee(2, 13, "F", "Martina", "Hengis");
Employee e5 = new Employee(5, 19, "F", "Cristine", "Maria");
Employee e7 = new Employee(7, 68, "F", "Melissa", "Roy");
Employee e9 = new Employee(9, 15, "F", "Neetu", "Singh");
Employee e1 = new Employee(1, 23, "M", "Rick", "Beethovan");
Employee e3 = new Employee(3, 43, "M", "Ricky", "Martin");
Employee e4 = new Employee(4, 26, "M", "Jon", "Lowman");
Employee e6 = new Employee(6, 15, "M", "David", "Feezor");
Employee e8 = new Employee(8, 79, "M", "Alex", "Gussin");
Employee e10 = new Employee(10, 45, "M", "Naveen", "Jain");
List<Employee> employees = new ArrayList<Employee>();
employees.addAll(Arrays.asList(new Employee[]{e1, e2, e3, e4, e5, e6, e7, e8, e9, e10}));
List<Predicate<Employee>> predicates = new ArrayList<>();
predicates.add(EmployeePredicates.isAdultFemale());
predicates.add(EmployeePredicates.firstNameLike("J"));
final Predicate<Employee> employeePredicate = predicates.stream().reduce(Predicate::and).get();
//OR adult male
employeePredicate.or(EmployeePredicates.isAdultMale());
final List<Employee> collect = employees.stream().filter(employeePredicate).collect(Collectors.toList());
System.out.println(collect.size());
根据我的逻辑,它应该检查列表
如果它的AdultFemale和名字像“J”或其成年男性
但这不符合逻辑.我在这做错了什么?即使员工是成人MALE,也会将其过滤掉.
解决方法:
or不会改变它所使用的Predicate对象,它会返回带有该逻辑的Predicate.在这里,既然您没有在任何丢失它的地方分配返回值,那么或者呼叫什么都不做.相反,您应该将其保存到变量中.例如.:
final Predicate<Employee> employeePredicate =
predicates.stream().reduce(Predicate::and).get();
// OR adult male
// Note that the result is saved back to employeePredicate
employeePredicate = employeePredicate.or(EmployeePredicates.isAdultMale());
内容总结
以上是互联网集市为您收集整理的应用OR谓词Java 8全部内容,希望文章能够帮你解决应用OR谓词Java 8所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。