使用Collections.frequency()打印某些值

ach*_*áin 6 java collections java-8 java-stream

我有一个数组如下:

int[] array = {11, 14, 17, 11, 48, 33, 29, 11, 17, 22, 11, 48, 18};
Run Code Online (Sandbox Code Playgroud)

我想要做的是找到重复的值,并打印它们.

所以我这样做的方法是转换为ArrayList,然后Set使用streamon 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);
Run Code Online (Sandbox Code Playgroud)

然后我用a stream循环遍历它并使用打印值Collections.frequency.

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

当然,即使计数为1,它们也会打印出来.

我想加入,if(key > 1)但这是我想要的价值不是关键.

如何在此实例中获取值以仅在哪里打印value > 2.

我可以投入:

int check = Collections.frequency(list, key);
            if (check > 1) {
Run Code Online (Sandbox Code Playgroud)

但是这会重复Collections.frequency(list, key),stream并且非常难看.

YCF*_*F_L 7

可能你只能用来filter获得大于2的值:

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

结果你的情况是:

11: 4
Run Code Online (Sandbox Code Playgroud)

编辑

另一种方案:

无需使用SetCollections.frequency您可以使用:

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()));
Run Code Online (Sandbox Code Playgroud)

产量

48: 2
17: 2
11: 4
Run Code Online (Sandbox Code Playgroud)