使用Collections.frequency()打印某些值 [英] Printing certain values using Collections.frequency()
问题描述
我有一个如下数组:
int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
我想要做的是找到重复的值,并打印出来。
What I wanted to do was to find the duplicate values, and print them.
所以我的方法是转换为 ArrayList
,然后转换为 Set
并在集
上使用流
。
So my way of doing this was to convert to ArrayList
, then to Set
and use a stream
on the Set
.
ArrayList<Integer> list = new ArrayList<>(array.length);
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
Set<Integer> dup = new HashSet<>(list);
然后我使用流
来循环它并使用 Collections.frequency
打印值。
I then used a stream
to loop through it and print the values using Collections.frequency
.
dup.stream().forEach((key) -> {
System.out.println(key + ": " + Collections.frequency(list, key));
});
当然,即使计数为1,也会将它们全部打印出来。
Which will of course print them all, even if the count is one.
我想在中添加if(key> 1)
,但这是我想要的值而不是密钥。
I thought adding in if(key > 1)
but it's the value I want not the key.
如何才能使此实例中的值仅在值>的位置打印2
。
How can I get the value in this instance to print only where value > 2
.
我可以投入:
int check = Collections.frequency(list, key);
if (check > 1) {
但这会重复
,并且非常丑陋。流
中的Collections.frequency(列表,密钥)
but this then duplicates Collections.frequency(list, key)
in the stream
and is quite ugly.
推荐答案
可能你可以使用过滤器
来获得大于2的值:
Probably you can to use filter
to get only the values great than 2 :
dup.stream()
.filter(t -> Collections.frequency(list, t) > 2)
.forEach(key -> System.out.println(key + ": " + Collections.frequency(list, key)));
结果你的情况是:
11: 4
编辑
Edit
另一个解决方案:
无需使用 Set
或 Collections.frequency
您可以使用:
No need to use a Set
or Collections.frequency
you can just use :
Integer[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
Arrays.stream(array).collect(Collectors.groupingBy(p -> p, Collectors.counting()))
.entrySet().stream().filter(t -> t.getValue() > 1)
.forEach(key -> System.out.println(key.getKey() + ": " + key.getValue()));
输出
48: 2
17: 2
11: 4
这篇关于使用Collections.frequency()打印某些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!