Refactor a method to using stream API

Not sure why people are involving keySet here when the required sum is only of List size contained in values. Just sum the size of all values.

return sqlFilesInDirectories.values().stream().mapToInt(List::size).sum();

And even the for loop version should be simply this,

for (List<Path> list : sqlFilesInDirectories.values()) {
    totalAmount += list.size();
}

As iterating over keyset and then getting value from map isn't really required and will not be better performance wise.


It's because in stream you're taking whole entries instead of values. This should do it:

totalAmount = sqlFilesInDirectories.values().stream().map(List::size).sum();

Other answers provide the shortest way to sum all entries, but if you need the amount of scripts per Path you can use the following:

Map<Path, Integer> amountOfFilesForPath =
        files.entrySet().stream().collect(Collectors.groupingBy(Map.Entry::getKey,
        Collectors.summingInt(value -> value.getValue().size())));

And you can also get the total value:

int sum = amountOfFilesForPath.values().stream().mapToInt(Integer::intValue).sum();