Combining a Collection of Predicates
public void whenFilterListWithCollectionOfPredicatesUsingAnd_thenSuccess(){ List<Predicate<String>> allPredicates = new ArrayList<Predicate<String>>(); allPredicates.add(str -> str.startsWith("A")); allPredicates.add(str -> str.contains("d")); allPredicates.add(str -> str.length() > 4); List<String> result = names.stream() .filter(allPredicates.stream().reduce(x->true, Predicate::and)) .collect(Collectors.toList()); assertEquals(1, result.size()); assertThat(result, contains("Alexander")); }
1 package fengliang.firstjava; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.*; 6 import java.util.function.Predicate; 7 8 class FilterContainer<T> { 9 protected List<T> list = new ArrayList<>(); 10 11 public FilterContainer<T> addFilter(T predicate) { 12 list.add(predicate); 13 return this; 14 } 15 16 public List<T> getList() { 17 return list; 18 } 19 } 20 public class LambdaExamination { 21 22 protected static List<Employee> createDepartment() { 23 24 return new ArrayList<>(Arrays.asList( 25 new Employee("张三", 12, "2012-11-12"), 26 new Employee("李四", 9, "2018-06-01"), 27 new Employee("王五", 11.5, "2019-06-01"), 28 new Employee("赵六", 11.2, "2018-11-02"), 29 new Employee("孙七", 8, "2020-08-08") 30 )); 31 } 32 33 protected static Comparator<Employee> sortBySalary() { 34 35 return Comparator.comparingDouble(Employee::getSalary); 36 } 37 38 protected static Date stringDateTimeFormat(String datetime) { 39 try { 40 return new SimpleDateFormat("y-MM-dd").parse(datetime); 41 } catch (ParseException e) { 42 e.printStackTrace(); 43 } 44 throw new RuntimeException("datetime的格式必须符合2020-02-01"); 45 } 46 47 protected static Comparator<Employee> sortByHireDay() { 48 return Comparator.comparing((Employee e) -> stringDateTimeFormat(e.getHireDay())); 49 } 50 51 protected static Predicate<Employee> filterBySalary(double salary) { 52 return (Employee e) -> Double.compare(e.getSalary(), salary) > 0; 53 } 54 55 protected static Predicate<Employee> filterByHireDay(String hireDay) { 56 return (Employee e) -> stringDateTimeFormat(e.getHireDay()).compareTo(stringDateTimeFormat(hireDay)) > 0; 57 } 58 59 public static void main(String[] args) { 60 List<Employee> department = createDepartment(); 61 FilterContainer<Predicate<Employee>> filterContainer = new FilterContainer<>(); 62 filterContainer.addFilter(filterBySalary(10.0)) 63 .addFilter(filterByHireDay("2018-10-10")); 64 65 department.stream().filter(filterBySalary(10)).filter( 66 filterContainer.getList().stream().reduce(f->true, Predicate::and) 67 ).sorted(sortBySalary()) 68 .forEach( 69 employee -> System.out.println(employee.name+", "+ employee.salary+", "+employee.hireDay.toString()) 70 ); 71 } 72 }
https://www.baeldung.com/java-predicate-chain