计算数组列表中的重复项

时间:2018-11-30 12:09:17

标签: java arrays jdk1.6

Arraylist al = new ArrayList();

Random r = new Random();

int arr[] = new int[100];

for (int i = 0; i < arr.length; i++) { // assuming the array variable is named arr...
    arr[i] = r.nextInt(200);
    al.add(arr[i]);
}

输出应该像这样

Duplicates:2

Values 2 : count=4

Values 99: count=96

不使用哈希值 杰克1.6_04

2 个答案:

答案 0 :(得分:2)

一个更简单的解决方案是:

al.stream().distinct()
                .forEach(v -> System.out.println("Values " + v + " : count=" + Collections.frequency(al, v)));

获取由不同元素组成的流,然后使用Collections.frequency()

计算列表中的元素数量

更新:如果不允许使用Java 8的功能:

Set<Integer> distinctSet = new HashSet<>(al);
for(int i: distinctSet) {
    System.out.println("Valuess " + i + " : count=" + Collections.frequency(al, i));
}

答案 1 :(得分:0)

这是解决问题的一种方法:

new Random().ints(100, 0, 200) // 100 is streamSize , 0 is randomNumberOrigin, 200 is randomNumberBound
            .boxed()
            .collect(groupingBy(Function.identity(), counting()))
            .forEach((k, v) -> System.out.println("Values " + k + " count" + v));

或者如果您希望结果在列表中:

List<String> result = new Random().ints(100, 0, 200) // 100 is streamSize , 0 is randomNumberOrigin, 200 is randomNumberBound
                .boxed()
                .collect(groupingBy(Function.identity(), counting()))
                .entrySet().stream()
                .map(e -> "Values " + e.getKey() + " count" + e.getValue())
                .collect(Collectors.toList());

另一种方法是使用toMap

List<String> res = new Random().ints(100, 0, 200) // 100 is streamSize , 0 is randomNumberOrigin, 200 is randomNumberBound
                .boxed()
                .collect(toMap(Function.identity(), e -> 1, Math::addExact))
                .entrySet().stream()
                .map(e -> "Values " + e.getKey() + " count" + e.getValue())
                .collect(Collectors.toList());

编辑:

假设您已经删除了Java 8标签,这是完整性的解决方案:

List<Integer> al = new ArrayList<>();
Set<Integer> accumulator = new HashSet<>();

Random r = new Random();

for (int i = 0; i < 100; i++) {
     int result = r.nextInt(200);
     al.add(result);
     accumulator.add(result);
}

for (Integer i : accumulator) {
     System.out.println("Values " + i + " : count=" + Collections.frequency(al, i));
}

+1 @@Hülya首先建议Collections.frequency