[java] 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;
        }
    }
}

This question is related to java

The answer is


Outside of your loop create an int:

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

Then in the loop, increment it:

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

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...


The only thing I would add to Mark Peters solution is that you don't need to iterate over the ArrayList - you should be able to use the addAll(Collection) method on the Set. You only need to iterate over the entire list to do the summations.


Using Java 8 stream API:

 String[] keys = new String[0];

// A map for keys and their count
Map<String, Long> keyCountMap = Arrays.stream(keys).
collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
int uniqueItemIdCount= keyCountMap.size();

You can get the number of elements in the list by calling list.size(), however some of the elements may be duplicates or null (if your list implementation allows null).

If you want the number of unique items and your items implement equals and hashCode correctly you can put them all in a set and call size on that, like this:

new HashSet<>(list).size()

If you want the number of items with a distinct itemId you can do this:

list.stream().map(i -> i.itemId).distinct().count()

Assuming that the type of itemId correctly implements equals and hashCode (which String in the question does, unless you want to do something like ignore case, in which case you could do map(i -> i.itemId.toLowerCase())).

You may need to handle null elements by either filtering them before the call to map: filter(Objects::nonNull) or by providing a default itemId for them in the map call: map(i -> i == null ? null : i.itemId).