Search code examples
graphunionjung

How to unite two graphs in JUNG?


I have to graphs which I want to unite, that is, create a new graph composed by the union of both graph's edges and nodes (without repetition). Is there an implementation for that avaliable in JUNG or do I have do so on my own?


Solution

  • There isn't an implementation for that in JUNG, but it's about six lines of code assuming that the graphs, vertices, and edges are of the same types:

    // given Graph g1, g2
    Graph g = new [appropriate Graph implementation]
    for (V v : Collections.union(g1.getVertices(), g2.getVertices())) {
      g.addVertex(v);
    }
    for (E e : g1.getEdges()) {
      g.addEdge(e, g1.getEndpoints(e));
    }
    for (E e : g2.getEdges()) {
      g.addEdge(e, g2.getEndpoints(e));
    }
    

    You can skip the vertex adding if there are no isolated vertices (i.e., vertices that have no incident edges); addEdge() will add any incident vertices.

    If the graph is directed, you'll want to change the above to

    g.addEdge(e, g1.getSource(e), g1.getDest(e));

    Duplicates are silently ignored (if you want to know whether an add had an effect, check the return value).