Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding number of values in a HashMap?

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.

like image 574
java123999 Avatar asked Mar 14 '16 16:03

java123999


2 Answers

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
like image 191
Suresh Atta Avatar answered Oct 15 '22 05:10

Suresh Atta


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());
like image 35
Clashsoft Avatar answered Oct 15 '22 03:10

Clashsoft