Count int occurrences with Java8

后端 未结 6 891
北恋
北恋 2020-11-27 06:12

Is there a better way to count int occurrences with Java8

int[] monthCounter = new int[12];
persons.stream().forEach(person -> monthCounter[person.getBirt         


        
6条回答
  •  抹茶落季
    2020-11-27 06:51

    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());
    

提交回复
热议问题