Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count int occurrences with Java8

Tags:

java

java-8

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]++); 
like image 549
Du_ Avatar asked May 29 '14 03:05

Du_


People also ask

How do you count numbers in Java 8?

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.

Is there a count method in Java?

The counting() method of the Java 8 Collectors class returns a Collector accepting elements of type T that counts the number of input elements.


2 Answers

Try:

 Map<Integer, Long> counters = persons.stream()      .collect(Collectors.groupingBy(p -> p.getBirthday().getMonthValue(),           Collectors.counting())); 
like image 91
Brian Goetz Avatar answered Oct 16 '22 22:10

Brian Goetz


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()); 
like image 36
Cuga Avatar answered Oct 17 '22 00:10

Cuga