我正在尝试填充哈希映射,键是节点度,值是具有该度值的所有节点的集合。现在我想出了这个代码:
// 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 是否有比我的代码更有效的类来完成这项任务。关键是我不仅需要度数分布,还要保存具有一定度数的节点集合。
无论如何,我感谢任何指向比我的更有效解决方案的指针。
最好的问候,西蒙娜