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 ?
Use the size() method to get the count of elements.
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.
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.
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.
As of Java 8 you accomplish that with an one-liner:
Integer sum = map.values().stream().mapToInt(List::size).sum();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With