Count the number of items in my array list
I want to count the number of itemids in my array, can i get an example of how i would go about adding this to my code. code below;
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;
}
}
}
Solution 1:
The number of itemId
s in your list will be the same as the number of elements in your list:
int itemCount = list.size();
However, if you're looking to count the number of unique itemIds (per @pst) then you should use a set to keep track of them.
Set<String> itemIds = new HashSet<String>();
//...
itemId = p.getItemId();
itemIds.add(itemId);
//... later ...
int uniqueItemIdCount = itemIds.size();
Solution 2:
You want to count the number of itemids in your array. Simply use:
int counter=list.size();
Less code increases efficiency. Do not re-invent the wheel...