Search code examples
javagraphiterationjgrapht

Java: JGraphT: Iterate through nodes


I'm trying to iterate through all nodes, so I can print them out for graphviz. What is the best way to do that using the JGraphT library?

public static void main(String[] args) {
    UndirectedGraph<String, DefaultEdge> g = new SimpleWeightedGraph<String, DefaultEdge>(DefaultEdge.class);

    String odp = "ODP";
    String cck = "CCK";
    String mfe = "MFE";

    g.addVertex(odp);
    g.addVertex(cck);
    g.addVertex(mfe);

    g.addEdge(odp, cck);
    g.addEdge(odp, mfe);

}

Also, how do I add edge weights?

Edit: This seems to work pretty well. But is there a better way?

    Set<DefaultEdge> edges = g.edgeSet();

    for (DefaultEdge e : edges) {
        gv.addln(String.format("\"%s\" -> \"%s\"", g.getEdgeSource(e), g.getEdgeTarget(e)));            
    }

Solution

  • Try using WeightedGraph instead of UndirectedGraph (in answer to your second question about adding weights):

    WeightedGraph<String, DefaultEdge> g = new SimpleWeightedGraph<String, DefaultEdge>(DefaultEdge.class);
    
    String odp = "ODP";
    String cck = "CCK";
    String mfe = "MFE";
    
    g.addVertex(odp);
    g.addVertex(cck);
    g.addVertex(mfe);
    
    DefaultEdge e1 = g.addEdge(odp, cck);
    DefaultEdge e1 = g.addEdge(odp, mfe);
    
    g.setEdgeWeight(e1, 10);
    g.setEdgeWeight(e2, 4);