Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of items in my array list

Tags:

java

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;         }     } } 
like image 717
user442471 Avatar asked Sep 13 '10 20:09

user442471


People also ask

How do you count items in an ArrayList?

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.

How do I count the number of items in a list in Java?

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.

How do you count arrays in Java?

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.


1 Answers

The number of itemIds 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(); 
like image 100
Mark Peters Avatar answered Sep 16 '22 11:09

Mark Peters