2013-10-11 44 views
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有一些一流的效率比我的代碼來完成這個任務。重點是我不僅需要度數分佈,還需要保存一定程度的節點集合。

無論如何,我很欣賞任何指向比我更高效的解決方案。

最好的問候, 西蒙娜

回答

0

你在做什麼本質上是正確的,但它可以更高效: *圖形已經有一定程度的()方法 *節點並不需要存儲的鄰居或程度;圖表爲你做這個 *你可以使用番石榴多地圖 *

+0

非常感謝你的時間!好的,只是用Guava MultiMap進行搜索,它看起來像R中的一個數據幀,因爲我的關鍵是行,並且我放入的任何條目都像一個新列,因此每個關鍵字都映射到我映射到的所有節點現在收藏 ......我明白了嗎? – user299791

+1

這就是這個想法。更簡單和更像Java的思考方式是Multimap 本質上是Map >的別名。它根據需要照顧創建集合等。 –

相關問題