Finding number of values in a HashMap?
If I understand the question correctly, you have a Map<String, List<Something>>
, and you want to count the total number of items in all the List
s in the Map
's values. Java 8 offers a pretty easy way of doing this by streaming the values, mapping them to their size()
and then just summing them:
Map<String, List<Something>> map = ...;
int totalSize = map.values().stream().mapToInt(List::size).sum());
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
Say you have a map
Map<String, List<Object>> map = new HashMap<>();
You can do this by calling the values()
method and calling size()
method for all the lists:
int total = 0;
Collection<List<Object>> listOfValues = map.values();
for (List<Object> oneList : listOfValues) {
total += oneList.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());