In Java 8, you can also use the Stream
API:
int total = map.values() .stream() .mapToInt(List::size)
This has the advantage that you do not need to repeat the List<Foo>
for the for variable, as in pre-Java 8:
int total = 0; for (List<Foo> list : map.values()) { total += list.size(); } System.out.println(total);
In addition to this, although not recommended, you can also use this value in a string without the need for the temp variable:
System.out.println(map.values().stream().mapToInt(List::size).sum());
source share