简体   繁体   中英

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

The number of itemId s 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();

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM