[英]Expanding a map of collections to a one dimensional map new “Cannot infer functional interface type”
I have some values in a map that I would like to transform to a simpler map where the key would be 'A' -> 1, 'E'-> 1,...'Z'-> 10
.我在 map 中有一些值,我想将其转换为更简单的 map ,其中键为'A' -> 1, 'E'-> 1,...'Z'-> 10
。 Keep getting "Cannot infer functional interface type".不断收到“无法推断功能接口类型”。
private Map<List<Character>, Integer> scoresMap
= Map.of(
List.of('A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'), 1,
List.of('D', 'G'), 2,
List.of('B', 'C', 'M', 'P'), 3,
List.of('F', 'H', 'V', 'W', 'Y'), 4,
List.of('K'), 5,
List.of('J', 'X'), 8,
List.of('Q', 'Z'), 10
);
I tried a functional approach:我尝试了一种功能方法:
private Stream<Map.Entry<Character, Integer>> expandMap(Map.Entry<List<Character>, Integer> kv){
return kv.getKey()
.stream()
.collect(
Stream.of(),
(Stream<Map.Entry<Character, Integer>> acc, char el) ->
Stream.concat(acc, Stream.of(Map.entry(el, kv.getValue()))),
(Stream<Map.Entry<Character, Integer>> acc, Stream<Map.Entry<Character, Integer>> el) -> Stream.concat(acc, el)
);
}
And tried forEach:并尝试了forEach:
private Map<Character, Integer> scores(){
Map<Character, Integer> scores = Map.of();
scoresMap
.entrySet()
.forEach(
(Map.Entry<List<Character>, Integer> kv) ->
kv.getKey().forEach(
(char k) ->
scores.put(k, kv.getValue());
)
)
return scores;
} }
I think this is not to do with ambiguous types as I tried using little helpers instead of Lambdas.我认为这与模棱两可的类型无关,因为我尝试使用小助手而不是 Lambdas。
You can make use of flatMap
:您可以使用flatMap
:
Map<Character, Integer> simpleMap = scoresMap.entrySet()
.stream()
.flatMap(entry -> {
Integer value = entry.getValue();
return entry.getKey().stream().map(ch -> Map.entry(ch, value));
})
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
You can use Map.forEach() directly and you don't have to bother with types, Java can figure it by itself.您可以直接使用 Map.forEach() 并且您不必为类型而烦恼,Java 可以自己计算。
private Map<Character, Integer> scores(){
Map<Character, Integer> scores = new HashMap<>();
scoresMap.forEach((key, value) ->
key.forEach((k) ->
scores.put(k, value)));
return scores;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.