[英]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)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.