What is the best / most efficient way to find the total number of Values in a HashMap
.
I do not mean the .size() method as it counts the number of keys. I want the total number of values in all the keys.
I want to do so as my key is a String
, but my value is a List
.
Easiest would be, iterate and add over list sizes.
int total = 0;
for (List<Foo> l : map.values()) {
total += l.size();
}
// here is the total values size
In Java 8, you can also utilize the Stream
API:
int total = map.values()
.stream()
.mapToInt(List::size) // or (l -> l.size())
.sum()
This has the advantage that you don't have to repeat the List<Foo>
type for a for
variable, as in the pre-Java 8 solution:
int total = 0;
for (List<Foo> list : map.values())
{
total += list.size();
}
System.out.println(total);
In addition to that, although not advised, you could also use that value inline without needing a temp variable:
System.out.println(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