0

我正在尝试填充哈希映射,键是节点度,值是具有该度值的所有节点的集合。现在我想出了这个代码:

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

但我想知道 JUNG 是否有比我的代码更有效的类来完成这项任务。关键是我不仅需要度数分布,还要保存具有一定度数的节点集合。

无论如何,我感谢任何指向比我的更有效解决方案的指针。

最好的问候,西蒙娜

4

1 回答 1

0

你所做的本质上是正确的,但可以提高效率: * Graph 已经有一个 degree() 方法 * 节点不需要存储邻居或度数;该图为您执行此操作 *您可以使用 Guava MultiMap *

于 2013-10-13T06:48:55.850 回答