Debug Java 8 filters

1k views Asked by At

I have employee object

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;

I have two predicates

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");
    }

I am applying multiple filters to the employees e.g.

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::or).get();


        final List<Employee> collect = employees.stream().filter(employeePredicate).collect(Collectors.toList());

This all works absolutely fine but what I want to be able to do is for each employee which filter was applied and print that. lets say

employee1 was filtered out because its not Female etc. Is that something possible?

1

There are 1 answers

1
Eran On

You can add debug prints to the predicates:

public static Predicate<Employee> firstNameLike(final String name) {
    return p -> {
        boolean passed = p.getFirstName().contains(name);
        if (!passed) {
            System.out.println(p.getFirstName() + " doesn't contain " + name);
        }
        return passed;
    }
}


public static Predicate<Employee> isAdultFemale() {
    return p -> {
        booolean passed = p.getAge() > 18 && p.getGender().equalsIgnoreCase("F");
        if (!passed) {
            System.out.println("employee not an adult female");
        }
        return passed;
    }
}