【发布时间】:2022-08-09 10:45:10
【问题描述】:
我正在尝试构建一个List 的类,这些类实现了一个名为Interface 的特定接口:
List<Class<? extends Interface>> myList= myMap.entrySet().stream()
.filter(entry -> entry.getValue().equals(myValue))
.map(Map.Entry::getKey) // Stream<Interface>
.map(Interface::getClass) // Stream<Class<capture of ? extends Interface>>
.distinct()
.toList();
我在调用 map() 之后添加了 Stream 中元素的类型作为注释。
代码遍历映射中的所有条目,如果它们的值等于myValue,则:
- 首先,获取实例
Interface类型(即钥匙的入口) - 然后,获取实现
Interface的Class。
myMap 定义为:
Map<Interface, Integer> myMap = new HashMap<>()
我得到的错误:
Incompatible types.
Found: \'java.util.List<java.lang.Class<capture<? extends application.interfaces.Interface>>>\',
required: \'java.util.List<java.lang.Class<? extends application.interfaces.Interface>>\'
我显然错过了一些关于如何泛型在Java中工作,但我在这里不知所措。我想这与编译器无法正确具体化我的? 通配符这一事实有关。
-
可能,你的意思是
entry.getValue().equals(myValue),不是entry.getValue() == myValue -
是的,感谢您的关注,我会更新帖子
标签: java generics java-stream