user680406
user680406

Reputation: 5747

Java: count the total number of items in a HashMap<String, ArrayList<String>>

I have this HashMap<String, ArrayList<Item>> , is there a way to count the total number of items in all the Lists in the Map without going through all Lists?

Or should I iterate through the Map and along all lists ?

Upvotes: 31

Views: 109943

Answers (8)

linqu
linqu

Reputation: 11980

As of Java 8 you accomplish that with an one-liner:

Integer sum = map.values().stream().mapToInt(List::size).sum();

Upvotes: 30

user3012970
user3012970

Reputation: 309

Use the size() method defined for HashMap.

HashMap<String, ArrayList<Item>> hMap = new LinkedHashMap<String, ArrayList<Item>>();
int hSize;
/*
    put/remove operations

*/

hSize = hMap.size(); // Gives the total no. of elements of HashMap

Upvotes: 16

user1530779
user1530779

Reputation: 509

If Any one still looking out for answers

Here is the code posted

    Iterator<Map.Entry<Integer, ArrayList<ShortListedFlats>>> iter = rentShortListedFlats
            .entrySet().iterator();

    while (iter.hasNext()) {
        ArrayList<ShortListedFlats> shortLists = iter.next().getValue();

        counter = counter + shortLists.size();

    }

Upvotes: -1

erikbstack
erikbstack

Reputation: 13254

Yes, you need a for loop:

public static int countItems(HashMap<String, ArrayList<Item>> yourMap){
    int counter = 0;
    for(ArrayList<Item>> list: yourMap.values()){
        counter += list.size();
    }
    return counter;
}

Upvotes: -2

Peter Lawrey
Peter Lawrey

Reputation: 533670

Multimap sounds like the right choice however, you could do

public static <K, V> int count(Map<K, ? extends Collection<V>> map) {
    int count = 0;
    for (Collection<V> coll : map.values()) count += coll.size();
    return count;
}

BTW: You may want count to return a long ;)

Upvotes: 2

WhiteFang34
WhiteFang34

Reputation: 72049

You'll need to iterate over the List<Item> values in your Map and count the total. The Map doesn't have any knowledge of what values you're putting into it, so it can't provide a facility to get you a total. The code you need is fairly simple:

int total = 0;
for (List<Item> list : map.values()) {
    total += list.size();
}

Upvotes: 7

nanda
nanda

Reputation: 24788

You might want to see Google Guava and use Multimap instead of that. The Multimap.size() method will give the answer you want.

Upvotes: 11

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116286

Since Map itself has no a priori knowledge about the values stored in it, except that they are Objects (thus can't be expected to perform any operations on them, other than calling toString(), equals() and/or hashCode()), there is no other way than iterating through its elements and calculating the sum manually.

Upvotes: 2

Related Questions