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 ?
As of Java 8 you accomplish that with an one-liner:
Integer sum = map.values().stream().mapToInt(List::size).sum();
Non-static method 'size' cannot be referenced from a static context errorUse 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
hMap.size () for the following key-values: ["key1", [Item1, Item2]], ["key2", [Item3, Item4]] would only return 2, instead we want 4 since there are 4 Item objectsmap.size()*2, I don't understand.map.size()*2 will not work for the example: ["key1", [Item1, Item2]], ["key2", [Item3, Item4, Item5, Item6]], since the total number of values is 6.You might want to see Google Guava and use Multimap instead of that. The Multimap.size() method will give the answer you want.
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();
}
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.
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 ;)
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();
}
Iterator approachfor(Map.Entry<Integer, ArrayList<ShortListedFlats>> entry : rentShortListedFlats.entrySet()) is equivalent but better readable than your code. @Peter Lawrey provided a superiour answer to yours.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;
}
HashMap does not implement Iterable so the outer for loop is a compilation error.