最近我想出了创建以下方法的想法:
/** Returns a {@link Predicate} which tests whether all its elements match a condition passed as argument. */
private static <T> Predicate<Iterable<T>> allIterableElementsMatch(Predicate<T> elementMatchCondition) {
return iterable -> stream(iterable).allMatch(elementMatchCondition);
}
然后我决定声明 Function
-field 而不是声明上面的方法。
我可以提供的最接近的无法编译解决方案是:
private static final Function<Predicate<?>, Predicate<Iterable<?>>> allIterableElementsMatch =
condition -> iterable -> stream(iterable).allMatch(condition);
由于以下原因,此代码未编译(IDE 突出显示 allMatch(...)
内的 condition
):
我的问题:
- 它可以通过这种方式实现吗?还是我只是误解了使用函数式接口(interface)的概念?
- 是否可以在
Function
-s 声明中专门化某些类型,就像我展示的方法一样?
最佳答案
对于类型系统,?
来自Predicate<?>
和?
来自Predicate<Iterable<?>>
是不同的东西。你可以这样做:
private static <T> Function<Predicate<T>, Predicate<Iterable<T>>> func() {
return condition -> iterable -> StreamSupport.stream(iterable.spliterator(), false).allMatch(condition);
}
关于java - 如何在函数式接口(interface)的直接声明中专门化类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64936012/