我正在尝试构建一个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();
Run Code Online (Sandbox Code Playgroud)
map()我添加了调用后 Stream 中元素的类型作为注释。
该代码迭代映射中的所有条目,如果它们的值等于myValue,则:
Interface(这是条目的键)Class实施Interface。myMap定义为:
Map<Interface, Integer> myMap = new HashMap<>()
Run Code Online (Sandbox Code Playgroud)
我收到的错误:
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>>'
Run Code Online (Sandbox Code Playgroud)
我显然错过了关于泛型在 Java 中如何工作的一些内容,但我在这里不知所措。我想这与编译器无法正确具体化我的通配符这一事实有关?。