2010-09-13 53 views
44

我想計算我的數組中的itemids數量,我可以得到一個關於如何將其添加到我的代碼中的示例。下面的代碼;計算我的數組列表中的項目數

if (value != null && !value.isEmpty()) { 
    Set set = value.keySet(); 
    Object[] key = set.toArray(); 
    Arrays.sort(key); 

    for (int i = 0; i < key.length; i++) { 
     ArrayList list = (ArrayList) value.get((String) key[i]); 

     if (list != null && !list.isEmpty()) { 
      Iterator iter = list.iterator(); 
      double itemValue = 0; 
      String itemId = ""; 

      while (iter.hasNext()) { 
       Propertyunbuf p = (Propertyunbuf) iter.next(); 
       if (p != null) { 
        itemValue = itemValue + p.getItemValue().doubleValue(); 
        itemId = p.getItemId(); 
       } 

       buf2.append(NL); 
       buf2.append("     " + itemId); 

      } 

      double amount = itemValue; 
      totalAmount += amount; 
     } 
    } 
} 
+5

我不認爲這個問題與示例代碼很好地相互配合。你在尋找'獨特'itemIds或相似的數量嗎? – 2010-09-13 20:38:12

回答

103

itemId在你的列表中的號碼將是相同的列表中的元素個數:

int itemCount = list.size(); 

但是,如果你正在尋找數(唯一itemIds數量per @ pst),那麼你應該使用一組來跟蹤它們。

Set<String> itemIds = new HashSet<String>(); 

//... 
itemId = p.getItemId(); 
itemIds.add(itemId); 

//... later ... 
int uniqueItemIdCount = itemIds.size(); 
2

你的循環之外創建一個int:

int numberOfItemIds = 0; 
for (int i = 0; i < key.length; i++) { 

然後在循環,增加它:

itemId = p.getItemId(); 
numberOfItemIds++; 
+0

該死的。我認爲Mark Peters在我做之前發佈了一個更好的解決方案。 – Freiheit 2010-09-13 20:45:07

+0

是的,當你已經有了原始數組的長度時,試圖通過一個循環來計算每一步都是沒有意義的。 – StriplingWarrior 2010-09-13 20:50:35

0

我想補充馬克彼得斯解決方案的唯一的事情是,你不需要迭代ArrayList - 你應該可以在Set上使用addAll(Collection)方法。您只需遍歷整個列表即可進行求和。

+0

該列表包含'Propertyunbuf'對象,而所需的集合包含字符串。你不能從一個到另一個使用addAll ...你需要類似Google Collection的轉換來做到這一點。 – 2010-09-14 03:49:26

+0

好點。雖然我相信如果Propertyunbuf對象的equals()方法使用itemId,則可以將您的集合聲明爲Propertyunbuf的集合並獲得相同的淨結果。仍然我更喜歡你的方法 - 我只是想探索選項和替代品:) – BigMac66 2010-09-14 11:57:17

12

您想要統計陣列中的itemid數量。簡單地使用:

int counter=list.size(); 

較少的代碼提高了效率。不要運行祖先的輪...