[英]How to make a Predicate from a custom list of Predicates in Java?
I'm relatively new to programming and I have been wondering for past two days how to make a Predicate that is made from a custom list of other Predicates. 我对编程比较陌生,过去两天我一直想知道如何制作一个由其他Predicates自定义列表组成的谓词。 So I've came up with some kind of solution. 所以我想出了一些解决方案。 Below is a code snippet that should give you an idea. 下面是一个代码片段,可以给你一个想法。 Because I have written it based on solely reading various pieces of documentations I have two questions: 1/ is it a good solution? 因为我是基于单独阅读各种文档而编写的,所以我有两个问题:1 /它是一个很好的解决方案吗? 2/ is there some other, recommended solution for this problem? 2 /是否有其他一些推荐的解决方案可以解决这个问题?
public class Tester {
private static ArrayList<Predicate<String>> testerList;
//some Predicates of type String here...
public static void addPredicate(Predicate<String> newPredicate) {
if (testerList == null)
{testerList = new ArrayList<Predicate<String>>();}
testerList.add(newPredicate);
}
public static Predicate<String> customTesters () {
return s -> testerList.stream().allMatch(t -> t.test(s));
}
}
You could have a static method that receives many predicates and returns the predicate you want: 您可以使用静态方法接收许多谓词并返回所需的谓词:
public static <T> Predicate<T> and(Predicate<T>... predicates) {
// TODO Handle case when argument is null or empty or has only one element
return s -> Arrays.stream(predicates).allMatch(t -> t.test(s));
}
A variant: 一个变种:
public static <T> Predicate<T> and(Predicate<T>... predicates) {
// TODO Handle case when argument is null or empty or has only one element
return Arrays.stream(predicates).reduce(t -> true, Predicate::and);
}
Here I'm using Stream.reduce
, which takes the identity and an operator as arguments. 这里我使用的是Stream.reduce
,它将标识和运算符作为参数。 Stream.reduce
applies the Predicate::and
operator to all elements of the stream to produce a result predicate, and uses the identity to operate on the first element of the stream. Stream.reduce
将Predicate::and
运算符应用于流的所有元素以生成结果谓词,并使用标识对流的第一个元素进行操作。 This is why I have used t -> true
as the identity, otherwise the result predicate might end up evaluating to false
. 这就是我使用t -> true
作为标识的原因,否则结果谓词最终可能会被评估为false
。
Usage: 用法:
Predicate<String> predicate = and(s -> s.startsWith("a"), s -> s.length() > 4);
Java Predicate has a nice function of AND which returns new Predicate which is evaluation of both predicates. Java Predicate有一个很好的AND函数,它返回新谓词,它是两个谓词的评估。 You can add them all into one with this. 您可以将它们全部添加到一个中。
https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html#and-java.util.function.Predicate- https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html#and-java.util.function.Predicate-
example : 例如:
Predicate<String> a = str -> str != null;
Predicate<String> b = str -> str.length() != 0;
Predicate<String> c = a.and(b);
c.test("Str");
//stupid test but you see the idea :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.