我正在尝试构建 Map<String, GraphNode<Character>>
来自 List<Pair<GraphNode<Character>, List<String>>>
对。但我面临的问题是它给出了错误提示 Type mismatch: cannot convert from Map<Object,Object>
至 Map<String,GraphNode<Character>>
.
我应该如何强制返回 Map<String,GraphNode<Character>>
List<Pair<GraphNode<Character>, List<String>>> pairs = lines.stream().map(line -> {
String[] split = line.split(":");
List<String> dest = Lists
.newArrayList(Splitter.on(",").trimResults().omitEmptyStrings().splitToList(split[1]));
GraphNode<Character> node = new GraphNode<>(split[0].toCharArray()[0]);
return new javafx.util.Pair<GraphNode<Character>, List<String>>(node, dest);
}).collect(Collectors.toList());
Map<String, GraphNode<Character>> graphMap = pairs.stream().map(pair -> pair.getKey())
.collect(Collectors.toMap(GraphNode::getData, pair -> pair));
最佳答案
你的 map
步骤错误,因为您要丢弃 List<String>
中的数据(Pair
的值部分),我假设你想在输出映射中。我建议使用 flatMap
改造 Stream<Pair<GraphNode<Character>, List<String>>>
到 Stream<Pair<GraphNode<Character>, ListString>>
.从那里,得到 Map<String, GraphNode<Character>>
是微不足道的。
Map<String, GraphNode<Character>> graphMap =
pairs.stream()
.flatMap(pair->pair.getValue().stream().map(s -> new javafx.util.Pair<GraphNode<Character>, String>(pair.getKey(), s)))
.collect(Collectors.toMap(Pair::getValue,Pair::getKey));
关于java强制返回类型为通用类型而不是对象类型以使用收集器和流构造映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50170479/