我有一个包含源和目标的列表列表。例如,
public static void main(String[] args) {
List<Edge> edges = new ArrayList<>();}
[“ A”,“ B”]
[“ A”,“ C”]
[“ A”,“ D”]
[“ B”,“ E”]
我想将其转换为哈希图,例如
HashMap<String,List<String>> map = new HashMap<String,List<String>>();
A:B,C,D
B:E
我该怎么做?
我拥有的功能
static class Edge {
public String source;
public String destination;
public Edge(String source, String destination) {
this.source = source;
this.destination = destination;
}
}
答案 0 :(得分:2)
您可以轻松做到:
Map<String, List<String>> collMap = edges.stream()
.collect(Collectors.groupingBy(Edge::getSource,
Collectors.mapping(Edge::getDestination, Collectors.toList())));
给出输出:
{A = [B,C,D],B = [E]}
答案 1 :(得分:1)
遍历每条边并将其添加到地图中:
for (Edge edge : edges) {
if (!map.containsKey(edge.source))
map.put(edge.source, new ArrayList<String>());
map.get(edge.source).add(edge.destination);
}