Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 773
user680406 Avatar asked Mar 31 '11 08:03

user680406


People also ask

How do you count the number of elements in a HashMap?

Use the size() method to get the count of elements.

How do you count elements in an ArrayList in Java?

The size of an ArrayList can be obtained by using the java. util. ArrayList. size() method as it returns the number of elements in the ArrayList i.e. the size.

How do you count items in Java?

The size() method of the List interface in Java is used to get the number of elements in this list. That is, this method returns the count of elements present in this list container.

How do you count the number of occurrences of an element in a Java 8 map?

With Eclipse Collections (formerly GS Collections), you can make use of a data structure called Bag that can hold the number of occurrences of each element. Using IntBag , the following will work: MutableList<Person> personsEC = ListAdapter. adapt(persons); IntBag intBag = personsEC.


1 Answers

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

Integer sum = map.values().stream().mapToInt(List::size).sum(); 
like image 112
linqu Avatar answered Oct 08 '22 10:10

linqu