如何知道Set在添加值时发现重复值的时间

时间:2015-02-02 11:21:15

标签: java

我有这个int数组,

int [] A = {1,2,3,1,5,2,2,2,2,4,1,2,3,1,1,2,1};

现在,如果我将它添加到一个集合中,它将只添加唯一值

Set<Integer> s = new HashSet<Integer>();

for (int i = 0; i < A.length; i++) {
        s.add(A[i]); 
}

System.out.println(s.toString());

但我怎么知道Set遇到重复值多少次?

例如,

在上面的数组中,在第一次迭代1上添加,在第二次迭代2上添加,在第三次迭代3上添加,但在第四次迭代1被跳过了。

现在我怎么知道设置跳过了4th值?

修改:我不想使用s.contains

6 个答案:

答案 0 :(得分:2)

如果元素已在Set中,则

s.add(A[i])将返回false。您所要做的就是检查该方法返回的值。

for (int i = 0; i < A.length; i++) {
    if (!s.add(A[i]))
        System.out.println(A[i] + " is already in the Set"); 
}

如果您想知道未添加元素的次数,请维护一个计数器。

答案 1 :(得分:2)

您可以在Java 8中执行频率计数

int [] a = {1,2,3,1,5,2,2,2,2,4,1,2,3,1,1,2,1};
Map<Integer, Long> countOfNumbers = IntStream.of(a).boxed()
        .collect(groupingBy(i -> i, counting()));
System.out.println(countOfNumbers);

打印

{1=6, 2=7, 3=2, 4=1, 5=1}

密钥将是数字,keySet()是这些密钥的集合,值将是计数。

Collectors.groupingBy(Function)构建一个Map,其中地图的键是Function的结果,值是所有值的列表。

i -> i说,我不想派生值或查找字段,我想使用该值作为键。

counting()说,我不想要一个数字列表,我只是想知道它有多少。

答案 2 :(得分:1)

如果已添加对象,则

add方法返回false

Set API

答案 3 :(得分:0)

使用 Guava 库中的com.google.common.collect.Multiset<E>

答案 4 :(得分:0)

public static void main(String[] args){
        int [] A = {1,2,3,1,5,2,2,2,2,4,1,2,3,1,1,2,1};
        Set<Integer> s = new HashSet<Integer>();

        for (int i = 0; i < A.length; i++) {

                System.err.println("index " + i + " "+ s.add(A[i]));

        }
        System.out.println(s.toString());
    }

索引0为真 index 1是的 index 2是的 索引3假 指数4是真的 索引5假 索引6假 索引7假 索引8错误 指数9是的 指数10假 索引11假 索引12假 指数13假 指数14假 指数15假 索引16假 [1,2,3,4,5]

答案 5 :(得分:0)

    int[] a = {1,2,3,1,5,2,2,2,2,4,1,2,3,1,1,2,1};

    int count = 0;

    Set<Integer> s = new HashSet<Integer>();

    for (int i = 0; i < a.length; i++) 
    {
        if (!s.add(a[i]))
        {
           count++;
        }
    }

    System.out.println("Set had encountered a duplicate value :" + count
            + "times");