Is there a better way to count int occurrences with Java8
int[] monthCounter = new int[12];
persons.stream().forEach(person -> monthCounter[person.getBirt
There's a few variations this could take.
You can use Collectors.summingInt() to use Integer instead of the Long in the count.
If you wanted to skip the primitive int array, you could store the counts directly to a List in one iteration.
Count the birth months as Integers
Map monthsToCounts =
people.stream().collect(
Collectors.groupingBy(p -> p.getBirthday().getMonthValue(),
Collectors.summingInt(a -> 1)));
Store the birth months in a 0-based array
int[] monthCounter = new int[12];
people.stream().collect(Collectors.groupingBy(p -> p.getBirthday().getMonthValue(),
Collectors.summingInt(a -> 1)))
.forEach((month, count) -> monthCounter[month-1]=count);
Skip the array and directly store the values to a list
List counts = people.stream().collect(
Collectors.groupingBy(p -> p.getBirthday().getMonthValue(),
Collectors.summingInt(a -> 1)))
.values().stream().collect(Collectors.toList());