Java 8 List<V> into Map<K, V> with Function



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

而不是循环(有效(

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

我尝试了以下解决方案:

toSet().stream()
.collect(Collectors.toMap(Pair.of(Function.identity(), Boolean.TRUE), 
this::methodAcceptingMap));

但是转换时出错:

Type mismatch: cannot convert from Pair<Function<Object,Object>,Boolean> 
to Function<? super T,? extends K>

我的地图

private Map<Pair<Type, Boolean>, BiConsumer<Pair<Type, Boolean>, Parameters>> map =
new HashMap<>();

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));

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

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

我不太明白你的例子。在循环for,您为每个值传递相同的 lambda。我认为这没有意义。如果你真的想要这样,你需要通过obj -> (pair, param) -> this.methodAcceptingMap(pair, param)

toSet().stream().collect(Collectors.toMap(
obj -> Pair.of(obj, Boolean.TRUE), 
obj -> (pair, param) -> this.methodAcceptingMap(pair, param)));

最新更新