2017-09-07 100 views
1

我有員工對象調試Java 8個過濾器

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

這一切工作完全正常,但什麼我希望能夠做的是針對過濾器應用和打印每個員工。可以說

employee1被過濾出來,因爲它不是女等等。這是可能的嗎?

+0

[同時使用Java流的謂詞過濾日誌過濾結果]的可能的複製(https://stackoverflow.com/questions/43555977/logging -the-result-of-filter-while-using-java-streams-filter-by-predicate) –

回答

0

您可以添加調試打印到謂詞:

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; 
    } 
} 
+0

我不想打印,而是列出應用的謂詞。可以使用StringBuilder來追加結果 – Makky