谓词的值提取器
Value extractor for Predicates
在 Java 8 中,Comparator
class 有这个 really nifty static method 通过使用 Function
到 Comparator
Function
的结果作为 Comparator
.
的输入
我想做的是能够将 Function
对象与 Predicate
等其他类型组合起来,以使我的代码更具可读性,并使我的功能操作更强大.
例如,假设有一个 Set<Person>
,其中 Person
有一个 public String getName()
方法。我希望能够过滤掉没有名称的 Person
对象。理想情况下,语法如下所示:
people.removeIf(Predicates.andThenTest(Person::getName, String::isEmpty));
是否有任何内置方法可以将 Function
与 Predicate
之类的东西组合在一起? 我知道 Function#andThen(Function)
,但这仅对将函数与其他函数组合有用,遗憾的是,Predicate
没有 extend Function<T, Boolean>
。
P.S。我也知道我可以使用像 p -> p.getName().isEmpty()
这样的 lambda,但我想要一种方法来用 Function
.
组合预先存在的 Predicate
对象
您可以像这样将 Predicate
转换为 Function
:
Predicate<String> p = String::isEmpty;
Function<String, Boolean> g = p::test; // predicate to function
Function<Boolean, String> f = Object::toString;
f.compose(g); // or g.andThen(f);
Java8 中没有内置谓词的值提取方法,但下一个最佳解决方案是自己实现它:
public class Predicates {
public static <T,R> Predicate<T> andThenTest(
Function<T,R> func, Predicate<R> pred) {
return t -> pred.test(func.apply(t));
}
}
感谢@Holger,这也可能是:
return func.andThen(pred::test)::apply;
在 Java 8 中,Comparator
class 有这个 really nifty static method 通过使用 Function
到 Comparator
Function
的结果作为 Comparator
.
我想做的是能够将 Function
对象与 Predicate
等其他类型组合起来,以使我的代码更具可读性,并使我的功能操作更强大.
例如,假设有一个 Set<Person>
,其中 Person
有一个 public String getName()
方法。我希望能够过滤掉没有名称的 Person
对象。理想情况下,语法如下所示:
people.removeIf(Predicates.andThenTest(Person::getName, String::isEmpty));
是否有任何内置方法可以将 Function
与 Predicate
之类的东西组合在一起? 我知道 Function#andThen(Function)
,但这仅对将函数与其他函数组合有用,遗憾的是,Predicate
没有 extend Function<T, Boolean>
。
P.S。我也知道我可以使用像 p -> p.getName().isEmpty()
这样的 lambda,但我想要一种方法来用 Function
.
Predicate
对象
您可以像这样将 Predicate
转换为 Function
:
Predicate<String> p = String::isEmpty;
Function<String, Boolean> g = p::test; // predicate to function
Function<Boolean, String> f = Object::toString;
f.compose(g); // or g.andThen(f);
Java8 中没有内置谓词的值提取方法,但下一个最佳解决方案是自己实现它:
public class Predicates {
public static <T,R> Predicate<T> andThenTest(
Function<T,R> func, Predicate<R> pred) {
return t -> pred.test(func.apply(t));
}
}
感谢@Holger,这也可能是:
return func.andThen(pred::test)::apply;