如何从Java的自定义谓词列表中创建谓词? [英] How to make a Predicate from a custom list of Predicates in Java?
问题描述
我对编程还比较陌生,在过去的两天里,我一直想知道如何制作一个由其他谓词的自定义列表构成的谓词.所以我想出了一种解决方案.下面是一个代码片段,应该可以给您一个想法.因为我是基于仅阅读各种文档而编写的,所以我有两个问题:1/这是一个好的解决方案吗?2/还有其他建议的解决方案吗?
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. 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? 2/ is there some other, recommended solution for this problem?
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));
}
一个变体:
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
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. This is why I have used t -> true
as the identity, otherwise the result predicate might end up evaluating to false
.
用法:
Predicate<String> predicate = and(s -> s.startsWith("a"), s -> s.length() > 4);
这篇关于如何从Java的自定义谓词列表中创建谓词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!