Count int occurrences with Java8

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

    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

提交回复
热议问题