Java – using collections Frequency() prints some values

I have an array as follows:

int[] array = {11,14,17,11,48,33,29,22,18};

What I want to do is find duplicate values and print them

So I do this by converting to ArrayList, and then setting and using the stream on 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);

Then I loop it with a stream and use collections Frequency prints the value

dup.stream().forEach((key) -> {
            System.out.println(key + ": " + Collections.frequency(list,key));
        });

Of course, even if the count is 1, they will print out

I want to add if (key > 1), but it is the value I want, not the key

How to get the value in this instance, print only at the value > 2

I can invest in:

int check = Collections.frequency(list,key);
            if (check > 1) {

However, this copies collections in the stream Frequency (list, key) and very ugly

Solution

Maybe you can use the filter to get only values greater than 2:

dup.stream()
       .filter(t -> Collections.frequency(list,t) > 2)
       .forEach(key -> System.out.println(key + ": " + Collections.frequency(list,key)));

As a result, your situation is:

11: 4

edit

Another option:

You do not need to use set or collections Frequency to use:

Integer[] array = {11,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()));

yield

48: 2
17: 2
11: 4
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>