[英]Accept multiple predicates as argument to method
I'm pretty new to Java and following a course to understand it better. 我是Java的新手,正在学习一门课程以更好地理解它。 In the
Test code
below we are supposed to be able to create a method that accepts multiple Predicate
. 在下面的
Test code
中,我们应该能够创建一个接受多个Predicate
的方法。 I can't seem to get it right. 我似乎无法正确解决。
Collections
seem logical but they can't be used. Collections
看似合乎逻辑,但不能使用。 so I thought Predicate<T>[] predicates
would suffice. 所以我认为
Predicate<T>[] predicates
就足够了。 But no success there. 但是那里没有成功。
public class Utils {
// public static <T> Predicate<T> anyPassPredicate(Predicate<T>[] predicates) {
public static <T> Predicate<T> anyPassPredicate(Collection<Predicate<T>> predicates) {
Predicate<T> pred = predicates.stream().reduce(Predicate::or).orElse(x->false);;
return pred;
}
public static <T> T firstAnyMatch(List<T> list, Predicate<T> predicate) {
for (T element : list) {
if (predicate.test(element)) {
return element;
}
}
return null;
}
}
Test code 测试码
public class Test {
public static void main(String[] args) {
List<String> words = Arrays.asList("Jan", "Jos", "Anna", "Pieter", "Johan");
Predicate<String> anyMatch = Utils.anyPassPredicate(s -> s.contains("o"), s -> s.length() > 5);
Utils.firstAnyMatch(words, anyMatch);
}
}
How is it possible to accept multiple Predicate
as argument to the method? 如何接受多个
Predicate
作为方法的参数?
In order for a method to accept an unspecified number of arguments of the same type, you need to use varargs , which is specified by an ellipsis 为了使方法可以接受数量不限的相同类型的参数,您需要使用varargs ,由省略号指定
static <T> Predicate<T> anyPassPredicate(Predicate<T>... predicates) {
return Arrays.stream(predicates)
.reduce(Predicate::or)
.orElse(x->false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.