Count the number of items in my array list

Viewed 317217

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;
        }
    }
}
6 Answers

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

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();
Related