应用OR谓词Java 8

时间:2017-09-09 12:38:29

标签: java filter java-8 predicate

我有员工对象

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());

根据我的逻辑,它应该检查列表

如果其AdultFemalefirstname like "J"或其Adult Male

但这不符合逻辑。我在这做错了什么?即使员工是成人男性,也要过滤掉。

1 个答案:

答案 0 :(得分:10)

or不会改变它所使用的Predicate对象,返回具有该逻辑的Predicate。在这里,由于您没有在任何丢失它的地方分配返回值,or调用什么都不做。相反,您应该将其保存到变量中。 E.g:

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());