0

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

user299791
  • 2,021
  • 3
  • 31
  • 57

1 Answers1

0

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 *

Joshua O'Madadhain
  • 2,704
  • 1
  • 14
  • 18
  • thank you very much for your time! Ok, just googled Guava MultiMap and it looks like a dataframe in R, in the sense that my key is the row and any entry I put is like a new column, so each key is mapped to all the nodes that I am mapping with the Collection right now... did I get your point? – user299791 Oct 13 '13 at 10:04
  • 1
    That's sort of the idea. A simpler and more Java-like way of thinking about it is that a Multimap is essentially an alias for a Map>. It takes care of creating the collections as needed, etc. – Joshua O'Madadhain Oct 13 '13 at 21:15