我在使用Optional.orElse(..)方法时遇到了意外的编译错误。我有一个具有泛型类型 E 的类,我正在尝试通过消费者进行过滤以找到足够的类,如果过滤没有给出结果,则使用提供的类。生成的 Consumer 稍后将用于接受类型 E 的元素。为了清楚起见,我注释掉了过滤器步骤。
当使用消费者列表时,一切正常:
// List of Consumer of super of c: works!
public void listMethod(Consumer<? super E> defaultConsumer) {
List<Consumer<? super E>> list = new ArrayList<>();
Consumer<? super E> consumer = list.stream()
//.filter(/*Some filtering which is not relevant*/)
.findAny()
.orElse(defaultConsumer);
}
但是,当使用任何内容到 Consumer 的 Map 时,orElse 处会发生编译错误:
//Map of Object to Consumer of super of C: compile error on orElse
public void mapMethod(Consumer<? super E> defaultConsumer) {
Map<Object, Consumer<? super E>> map = new HashMap<>();
Consumer<? super E> consumer = map.entrySet()
.stream()
//.filter(/*Some filtering which is not relevant*/)
.map(Map.Entry::getValue)
.findAny()
.orElse(defaultConsumer);
}
错误信息是:
The method orElse(Consumer<capture#3-of ? super E>) in the type Optional<Consumer<capture#3-of ? super E>> is not applicable for the arguments (Consumer<capture#6-of ? super E>)
谁能澄清这里出了什么问题吗?谢谢:)
编辑:这是在 jdk1.8.0_45 上。
最佳答案
这似乎是 Eclipse Mars Java 编译器的问题。
Eclipse 有自己的编译器,不使用 javac。
javac 1.8.0_45
在我的机器上没有问题,而 Eclipse Mars 显示您所描述的错误。
关于java - 使用泛型类型中的 super 将 Map 流式传输到 Consumer 后使用 orElse 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496890/