Is there a better way to count int occurrences with Java8
int[] monthCounter = new int[12]; persons.stream().forEach(person -> monthCounter[person.getBirthday().getMonthValue() - 1]++);
Java 8 | Collectors counting() with ExamplesCollectors counting() method is used to count the number of elements passed in the stream as the parameter. It returns a Collector accepting elements of type T that counts the number of input elements. If no elements are present, the result is 0.
The counting() method of the Java 8 Collectors class returns a Collector accepting elements of type T that counts the number of input elements.
Try:
Map<Integer, Long> counters = persons.stream() .collect(Collectors.groupingBy(p -> p.getBirthday().getMonthValue(), Collectors.counting()));
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<Integer, Integer> 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<Integer> counts = people.stream().collect( Collectors.groupingBy(p -> p.getBirthday().getMonthValue(), Collectors.summingInt(a -> 1))) .values().stream().collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With