Java 8 List<V> 到 Map<K, V> 和函数

use*_*900 3 java dictionary set java-8 java-stream

我试图按照Java 8 List 进入 Map并尝试在一个列表中更改 Set to Map

而不是循环(有效)

for (Type t : toSet()) {
    map.put(Pair.of(t, Boolean.TRUE), this::methodAcceptingMap);
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下解决方案:

toSet().stream()
       .collect(Collectors.toMap(Pair.of(Function.identity(), Boolean.TRUE), 
                                 this::methodAcceptingMap));
Run Code Online (Sandbox Code Playgroud)

但在转换时出错:

Type mismatch: cannot convert from Pair<Function<Object,Object>,Boolean> 
to Function<? super T,? extends K>
Run Code Online (Sandbox Code Playgroud)

我的地图

private Map<Pair<Type, Boolean>, BiConsumer<Pair<Type, Boolean>, Parameters>> map =
      new HashMap<>();
Run Code Online (Sandbox Code Playgroud)

ern*_*t_k 6

Collectors.toMap 需要两个函数,你的参数都不适合。

你应该使用:

Map<Pair<Type, Boolean>, BiConsumer<Pair<Type, Boolean>, Parameters>> map =
    set.stream()
       .collect(Collectors.toMap(el -> Pair.of(el, Boolean.TRUE), 
                                 el -> this::methodAcceptingMap));
Run Code Online (Sandbox Code Playgroud)

该表达式Pair.of(t, Boolean.TRUE)根本不是一种Function类型。并且this::methodAcceptingMap可以适合 a 的签名BiConsumer,但该方法需要一个函数。所以el -> this::methodAcceptingMap应该用作一个函数,它接受一个流元素并返回你的BiConsumer.

请注意,map =在这种情况下,赋值上下文 ( ) 很重要。没有它,这些 lambda 表达式的目标类型将丢失,编译将失败。