Count the number of elements in an array list

I want to count the number of elements in my array, can I get an example of how I would like to add 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; } } } 
+57
java
Sep 13 '10 at 20:36
source share
4 answers

The number of itemId in your list will be the same as the number of items in your list:

 int itemCount = list.size(); 

However, if you want to count the number of unique itemIds (per @pst), you must use a set to track them.

 Set<String> itemIds = new HashSet<String>(); //... itemId = p.getItemId(); itemIds.add(itemId); //... later ... int uniqueItemIdCount = itemIds.size(); 
+128
Sep 13 '10 at 20:43
source share
— -

You want to count the number of elements in an array. Just use:

 int counter=list.size(); 

Less code improves efficiency. Do not start the wheel of the ancestors ...

+13
Oct 04 2018-11-11T00:
source share

Outside of your loop, create an int:

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

Then in a loop add it:

 itemId = p.getItemId(); numberOfItemIds++; 
+2
Sep 13 '10 at 20:44
source share

The only thing I would like to add to the Mark Peters solution is that you do not need to iterate over the ArrayList - you should be able to use the addAll (Collection) method in Set. You just need to iterate over the entire list to perform the summation.

0
Sep 13 '10 at 20:58
source share



All Articles