使用 Java8 计算 int 出现次数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23925315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count int occurrences with Java8
提问by Du_
Is there a better way to count int occurrences with Java8
有没有更好的方法来计算 Java8 的 int 出现次数
int[] monthCounter = new int[12];
persons.stream().forEach(person -> monthCounter[person.getBirthday().getMonthValue() - 1]++);
采纳答案by Brian Goetz
Try:
尝试:
Map<Integer, Long> counters = persons.stream()
.collect(Collectors.groupingBy(p -> p.getBirthday().getMonthValue(),
Collectors.counting()));
回答by itohro
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.
使用Eclipse Collections(以前称为GS Collections),您可以使用一种称为Bag
可以保存每个元素出现次数的数据结构。
Using IntBag
, the following will work:
使用IntBag
,以下将起作用:
MutableList<Person> 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 Brianpointed out in another answer.
如果您想使用数组来跟踪计数,您可以结合Brian在另一个答案中指出的Arrays.setAll()
方法。
int[] monthCounter = new int[12];
MutableList<Person> 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.
如果您使用匿名内部类而不是 lambda,此代码也适用于 Java 5 – 7。
Note: I am a committer for Eclipse Collections
注意:我是 Eclipse Collections 的提交者
回答by Huy Le
int size = persons.stream().count()
回答by avigaild
If you would like to get Integer to Integer map, you can do the following.
如果您想获得 Integer 到 Integer 映射,您可以执行以下操作。
Map<Integer, Integer> counters = persons.stream()
.collect(Collectors.groupingBy(
p -> p.getBirthday().getMonthValue(),
Collectors.reducing(0, e -> 1, Integer::sum)));
回答by Arjun Nagathankandy
Already answered. Small Suggestion from my side inorder to eliminate nullpointer exception ie From the stream null will throw java.lang.UnsupportedOperationException, java.lang.NullPointerException
已经回答了。我这边的小建议是为了消除空指针异常,即从流中 null 将抛出java.lang.UnsupportedOperationException, java.lang.NullPointerException
Map<Integer, Long> 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()));
回答by Cuga
There's a few variations this could take.
这可能会有一些变化。
You can use Collectors.summingInt()
to use Integer
instead of the Long
in the count.
您可以使用Collectors.summingInt()
toInteger
代替Long
in 计数。
If you wanted to skip the primitive int
array, you could store the counts directly to a List
in one iteration.
如果您想跳过原始int
数组,您可以将计数直接存储到List
一次迭代中。
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
将出生月份存储在基于 0 的数组中
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());