使用Java8计算int出现次数

有没有更好的方法来计算Java8的出现次数

int[] monthCounter = new int[12]; persons.stream().forEach(person -> monthCounter[person.getBirthday().getMonthValue() - 1]++); 

尝试:

  Map counters = persons.stream() .collect(Collectors.groupingBy(p -> p.getBirthday().getMonthValue(), Collectors.counting())); 

使用Eclipse Collections (以前称为GS Collections ),您可以使用名为Bag的数据结构,该结构可以保存每个元素的出现次数。

使用IntBag ,以下内容将起作用:

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

如果你想使用一个数组来跟踪计数,你可以结合Brian在另一个答案中指出的Arrays.setAll()方法。

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

如果您使用匿名内部类而不是lambdas,此代码也适用于Java 5 – 7。

注意:我是Eclipse Collections的提交者

 int size = persons.stream().count()