使用具有自定义功能接口的流

Using streams with custom functional interfaces

我刚刚开始查看 this Oracle website 上的流。看到下面这样的代码,我立即想到的一个问题是:如果我想重用过滤器逻辑怎么办,例如在 Person 中有方法 "isAdult"?

这在流中不能用作方法引用,因为它不接受参数 Person。类似地,我将无法创建一个接受年龄的附加 int 参数的过滤器来创建可参数化的 "isOlderThan" 逻辑。

我找不到将流与自定义功能接口结合使用的方法。你会如何模拟这种行为?在我看来,在上述场景中创建静态 "isAdult" 方法不是一个非常干净的解决方案,使用此类方法创建 "PersonChecker" 对象也不是。

List<Person> list = roster.parallelStream().filter((p) -> p.getAge() > 18).collect(Collectors.toList()); 

谢谢

List<Person> list = roster.parallelStream().filter((p) -> p.getAge() > 18).collect(Collectors.toList());

what if I want to reuse the filter logic, e.g. having a method "isAdult" in Person?

List<Person> list = roster.parallelStream().filter(Person::isAdult).collect(Collectors.toList());

List<Person> list = roster.parallelStream().filter(p -> p.isAdult()).collect(Collectors.toList());

I would not be able to create a filter which accepts and additional int parameter with an age to create a parameterisable "isOlderThan" logic.

List<Person> list = roster.parallelStream().filter(p -> p.isOlderThan(18)).collect(Collectors.toList());

我看不出自定义功能接口与您的问题有什么关系。 Predicate 是您在这里唯一需要的功能接口,lambda 和方法引用是创建 Predicate 实例的极其简单的方法。