【发布时间】:2020-10-05 23:47:55
【问题描述】:
class CollectorUtils {
private CollectorUtils() {
}
public static <T> Collector<T, ?, T> onlyElement() {
return Collectors.collectingAndThen(Collectors.toList(), Iterables::getOnlyElement);
}
public static <T> Collector<T, ?, Optional<T>> optionalElement() {
return Collectors.collectingAndThen(Collectors.toList(), (list) -> {
return Optional.ofNullable(Iterables.getOnlyElement(list, (Object)null));
});
}
public static <T> Collector<T, ?, List<T>> toList() {
return Collectors.toCollection(ArrayList::new);
}
}
我得到推理变量 T 的边界不兼容。
java:不兼容的类型:推理变量 T 具有不兼容的边界 等式约束:T 下界:T,java.lang.Object,T
【问题讨论】:
-
你能显示minimal reproducible example吗?
Iterables.getOnlyElement是什么? -
当询问编译器错误时,请包括行号,或以其他方式指出编译器正在标记哪个节点。此外,请考虑粘贴任何涉及的代码,例如 Iterables.getOnlyElement。
-
如果你完全使用 Guava 来获取
Iterables.getOnlyElement,为什么不使用these collectors from that library?
标签: java java-stream guava optional