Count int occurrences with Java8

后端 未结 6 923
北恋
北恋 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:40

    Already answered. Small Suggestion from my side inorder to eliminate null pointer exception ie From the stream null will throw java.lang.UnsupportedOperationException, java.lang.NullPointerException

    Map birthdayCount = persons.stream()
                                        .filter(Objects::nonNull) // filter out null object
                                        .filter(p->Objects.nonNull(p.getBirthday())) // filter out null birthdays
                                        .collect(Collectors.groupingBy(p -> 
                                                     p.getBirthday().getMonthValue(), 
                                                     Collectors.counting()));
    

提交回复
热议问题