Count the number of items in my array list

Java

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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++;

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser442471View Question on Stackoverflow
Solution 1 - JavaMark PetersView Answer on Stackoverflow
Solution 2 - Javaanand.CitizenView Answer on Stackoverflow
Solution 3 - JavaFreiheitView Answer on Stackoverflow
Solution 4 - JavaAlex - GlassEditor.comView Answer on Stackoverflow
Solution 5 - JavaEhab QadahView Answer on Stackoverflow
Solution 6 - JavaBigMac66View Answer on Stackoverflow