我在一个映射中有一些值,我想将它们转换为一个更简单的映射,即键所在的位置'A' -> 1, 'E'-> 1,...'Z'-> 10
。继续得到“无法推断函数接口类型”。
private Map, 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
);
我尝试了一种函数式方法:
private Stream> expandMap(Map.Entry, Integer> kv){
return kv.getKey()
.stream()
.collect(
Stream.of(),
(Stream> acc, char el) ->
Stream.concat(acc, Stream.of(Map.entry(el, kv.getValue()))),
(Stream> acc, Stream> el) -> Stream.concat(acc, el)
);
}
并尝试了forEach:
private Map scores(){
Map scores = Map.of();
scoresMap
.entrySet()
.forEach(
(Map.Entry, Integer> kv) ->
kv.getKey().forEach(
(char k) ->
scores.put(k, kv.getValue());
)
)
return scores;
}
我认为这与模棱两可的类型无关,因为我尝试使用小帮助器而不是Lambdas。
发布于 2021-01-17 04:58:19
您可以使用flatMap
Map 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));
发布于 2021-01-17 05:13:42
您可以直接使用Map.forEach(),您不必为类型而烦恼,Java可以自己计算它。
private Map scores(){
Map scores = new HashMap<>();
scoresMap.forEach((key, value) ->
key.forEach((k) ->
scores.put(k, value)));
return scores;
}
https://stackoverflow.com/questions/65754471
复制相似问题