BiFunction: 整合两个函数的方法。
为什么BiFunction不提供 compose ,只提供andThen呢?
因为如果提供compose方法的话,只能获取一个参数的返回值。不合理。
测试 函数式接口的实例:
public class PersonTest { public static void main(String[] args) { List<Person> personList = new ArrayList<>(); personList.add(new Person("zhangsan", 20)); personList.add(new Person("zhangsan", 28)); personList.add(new Person("lisi", 30)); personList.add(new Person("wangwu", 40)); PersonTest test = new PersonTest(); //测试 getPersonUsername // List<Person> personList1 = test.getPersonUsername("zhangsan", personList); // personList1.forEach(person -> System.out.println(person.getUsername())); //测试 getPersonByAge List<Person> personByAge = test.getPersonByAge(25, personList); personByAge.forEach(person -> System.out.println(person.getAge())); //测试第三种: 自定义输入行为 List<Person> list = test.getPersonByAge2(20,personList,(age,persons) ->{ return persons.stream().filter(person -> person.getAge() > age).collect(Collectors.toList()); }); list.forEach(person -> System.out.println(person.getAge())); } public List<Person> getPersonUsername(String username, List<Person> personList) { return personList.stream().filter(person -> person.getUsername().equals(username)).collect(Collectors.toList()); } public List<Person> getPersonByAge(int age, List<Person> personList) { //使用BiFunction的方式 // BiFunction<Integer, List<Person>, List<Person>> biFunction = (ageOfPerson, list) -> { // return list.stream().filter(person -> person.getAge() > ageOfPerson ).collect(Collectors.toList()); // }; //变换之后: BiFunction<Integer, List<Person>, List<Person>> biFunction = (ageOfPerson, list) -> list.stream().filter(person -> person.getAge() > ageOfPerson ).collect(Collectors.toList()); return biFunction.apply(age, personList); } //第三种方式, 动作也让用户自己定义传进来 public List<Person> getPersonByAge2(int age ,List<Person> list,BiFunction<Integer,List<Person>,List<Person>> biFunction){ return biFunction.apply(age, list); } }