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; } } }
You can use the size() method of java. util. ArrayList to find the length or size of ArrayList in Java. The size() method returns an integer equal to a number of elements present in the array list.
The size() method of the List interface in Java is used to get the number of elements in this list. That is, this method returns the count of elements present in this list container.
Java doesn't have the concept of a "count" of the used elements in an array. To get this, Java uses an ArrayList . The List is implemented on top of an array which gets resized whenever the JVM decides it's not big enough (or sometimes when it is too big). To get the count, you use mylist.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With