检查列表中的元素是否唯一的有效方法是什么?

时间:2014-06-16 08:20:52

标签: java list

在Java中检查列表中的元素是否唯一(没有其他具有相同值的元素)的有效方法是什么?

2 个答案:

答案 0 :(得分:8)

Collections.frequency在这里很有用:

public static <T> boolean hasDuplicates(List<T> list, T element) {
    return Collections.frequency(list, element) > 1;
}

这是线性的,因此在大型列表上可能会很慢。但是,如果您需要使用List,则无法提高效果,最多可以利用提前退出来减少平均运行时间:

public static <T> boolean hasDuplicates(List<T> list, T element) {
    int count = 0;
    for (T other: list) {
        // Ugly, but necessary to ensure null-safety
        boolean areEquals = (other == null)? element == null : other.equals(element);
        if (areEquals) {
            count += 1;
            if (count > 1) {
                return true;
            }
        }
    }
    return false;
}

答案 1 :(得分:-2)

为了提高性能,您可以执行以下操作:

  1. 将列表转换为如下设置:

    Set<Employee> employeeSet = new HashSet<Employee>(employeeList);
    
  2. 现在,对于每个传入元素,您可以检查add方法返回的值是false还是true,如下所示:

    boolean bool = employeeSet .add(dupEmployee);
    if(bool)
       // do this
    else 
      // do that
    
  3. 注意:您必须确保在hashCode课程中使用equalsEmployee方法。