在Java中将列表列表转换为HashTable

时间:2019-03-20 16:41:02

标签: java graph hashmap

我有一个包含源和目标的列表列表。例如,

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;
     }
   }

2 个答案:

答案 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);
}