Is there a better way to count int occurrences with Java8
int[] monthCounter = new int[12];
persons.stream().forEach(person -> monthCounter[person.getBirt
With Eclipse Collections (formerly GS Collections), you can make use of a data structure called Bag that can hold the number of occurrences of each element.
Using IntBag, the following will work:
MutableList personsEC = ListAdapter.adapt(persons);
IntBag intBag = personsEC.collectInt(person -> person.getBirthDay().getMonthValue()).toBag();
intBag.forEachWithOccurrences((month, count) -> System.out.println("Count of month:" + month + " is " + count));
If you want to make use of an array to keep track of the count, you can combine with the Arrays.setAll() approach Brian pointed out in another answer.
int[] monthCounter = new int[12];
MutableList personsEC = ListAdapter.adapt(persons);
IntBag bag = personsEC.collectInt(person -> person.getBirthDay().getMonthValue()).toBag();
Arrays.setAll(monthCounter, bag::occurrencesOf);
System.out.println(IntLists.immutable.with(monthCounter));
This code will also work with Java 5 – 7 if you use anonymous inner classes instead of lambdas.
Note: I am a committer for Eclipse Collections