小编ral*_*los的帖子

Java 泛型:Stream.map() 返回“捕获?” 代替 ”?”

我正在尝试构建一个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,则:

  • 首先,获取type 的实例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 中如何工作的一些内容,但我在这里不知所措。我想这与编译器无法正确具体化我的通配符这一事实有关?。

java generics java-stream

8
推荐指数
1
解决办法
793
查看次数

标签 统计

generics ×1

java ×1

java-stream ×1