使用Java Streams和泛型,我试图创建一个Collector
,如果stream为空,则返回Optional.empty
,如果stream有一个项,则返回Optional<T>
,如果stream有多个项,则抛出异常.
public static <T, R extends Optional<T>> Collector<T, ?, R> toOptional() {
return Collectors.collectingAndThen(
Collectors.toList(),
list -> {
if (list.size() > 1) {
throw new CollectingException("More than one item found in: " + list);
}
if (list.size() == 1) {
return Optional.of(list.get(0));
}
return Optional.empty();
}
);
}
然而,我收到了一个我不理解的错误.
Required type:
Collector<T,?,R>
Provided:
Collector<Object,Object,Object>
no instance(s) of type variable(s) T exist so that Optional<T> conforms to R inference variable RR has incompatible bounds: equality constraints: R lower bounds: Optional<T1868063>
所需的用法将是
List<Person> people = new ArrayList<>();
Optional<Person> john = people.stream().filter(person->"John".equals(person.getName())).collect(toOptional());
有谁能给我解释一下出什么事了吗?