Question

I am trying to fill an hash map were keys are nodes degree and values are a Collection of all the nodes with that degree value. Right now I came up with this code:

// hashmap to hold the result 
HashMap<Integer, Collection<Node>> result = new HashMap<Integer, Collection<Node>>();
// for each node in the list
for (Node n : nodes) {
    // find node's neighbors
    n.setNei(g.getNeighbors(n));
    // find node's degree
    n.setDegree(n.getNei().size());
    // placeholder
    Integer degree = n.getDegree();
    // if that degree is already present as a key in result
    if (result.containsKey(degree)) {
        // add n to the list of nodes that has that degree value
        boolean add = result.get(degree).add(n);
        // check
        if (!add) {
            // raise exception
            throw new ExtensionException("ERROR: failed to add node to list of nodes with degree " + degree);
        }
        // if that degree is not already present in result
    } else {
        // create a new empty collection of nodes
        List<Node> newList = new ArrayList<Node>();
        // add n as the first element in the new collection
        boolean add = newList.add(n);
        // check
        if (add) {
            // add degree to the key and the collection of nodes with such degree
            result.put(degree, newList);
        } else {
            // raise exception
            throw new ExtensionException("ERROR: failed to add node to list of nodes with degree " + degree);
        }
    }
}

but I wonder if JUNG has some class more efficient than my code to accomplish this task. The point is that I need to have not only the degree distribution, but also I want to save the collection of nodes with a certain degree.

In any case, I appreciate any pointer to more efficient solutions than mine.

Best regards, Simone

Was it helpful?

Solution

What you're doing is in essence correct but it can be made more efficient: * Graph already has a degree() method * Node doesn't need to store neighbors or degree; the graph does this for you * you can use a Guava MultiMap *

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top