将列表的列表转换为Java中的Hashtable



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

public static void main(String[] args) {
 List<Edge> edges = new ArrayList<>();}

[" a"," b"]

[" a"," c"]

[" a"," d"]

[" b"," e"]

我想将其转换为hashmap,例如

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

您可以简单地做:

Map<String, List<String>> collMap = edges.stream()
            .collect(Collectors.groupingBy(Edge::getSource, 
                     Collectors.mapping(Edge::getDestination, Collectors.toList())));

给出输出:

{a = [b,c,d],b = [e]}

在每个边缘上迭代并将其添加到您的地图上:

for (Edge edge : edges) {
    if (!map.containsKey(edge.source)) 
        map.put(edge.source, new ArrayList<String>());
    map.get(edge.source).add(edge.destination);
}

最新更新