java8--- Predicate 意义 代码

 //为了去除 DiyInterface 这个函数式接口,可以用通用函数式接口 Predicate 替代如下: https://blog.csdn.net/u011848397/article/details/89074794
    public class People2{
        private List<Person> persons= new ArrayList<>();
        public List<Person> getMaleList(Predicate<Person> predicate) {//通用函数式接口
            List<Person> res = new ArrayList<>();
            persons.forEach(person -> {
                if (predicate.test(person)) {//调用 Predicate 的抽象方法 test
                    res.add(person);
                }
            });
            return res;
        }
    }

    //还原:
    interface DiyInterface {
         boolean test(Person person);
    }
    public class People {
        private List<Person> persons= new ArrayList<Person>();
        public List<Person> getMaleList(DiyInterface filter) {//自定义函数式接口
            List<Person> res = new ArrayList<>();
            persons.forEach((Person person) -> {
                if (filter.test(person)) {
                    //调用 PersonInterface 的方法
                    res.add(person);
                }
            });
            return res;
        }
    }
   
    public class Person {
    }

猜你喜欢

转载自www.cnblogs.com/hahajava/p/12074751.html