我有一个ArrayList<String>,我想从它中删除重复的字符串。我该怎么做呢?


当前回答

你也可以这样做,保持秩序:

// delete duplicates (if any) from 'myArrayList'
myArrayList = new ArrayList<String>(new LinkedHashSet<String>(myArrayList));

其他回答

可能有点夸张,但我喜欢这种孤立的问题。:)

这段代码使用了一个临时Set(用于唯一性检查),但直接删除原始列表中的元素。由于在ArrayList中删除元素会导致大量的数组复制,因此可以避免使用remove(int)-方法。

public static <T> void removeDuplicates(ArrayList<T> list) {
    int size = list.size();
    int out = 0;
    {
        final Set<T> encountered = new HashSet<T>();
        for (int in = 0; in < size; in++) {
            final T t = list.get(in);
            final boolean first = encountered.add(t);
            if (first) {
                list.set(out++, t);
            }
        }
    }
    while (out < size) {
        list.remove(--size);
    }
}

说到这里,下面是LinkedList的一个版本(好多了!)

public static <T> void removeDuplicates(LinkedList<T> list) {
    final Set<T> encountered = new HashSet<T>();
    for (Iterator<T> iter = list.iterator(); iter.hasNext(); ) {
        final T t = iter.next();
        final boolean first = encountered.add(t);
        if (!first) {
            iter.remove();
        }
    }
}

使用标记界面为List提供统一的解决方案:

public static <T> void removeDuplicates(List<T> list) {
    if (list instanceof RandomAccess) {
        // use first version here
    } else {
        // use other version here
    }
}

编辑:我猜泛型的东西并没有真正增加任何价值在这里。哦。:)

你可以在下面使用嵌套循环:

ArrayList<Class1> l1 = new ArrayList<Class1>();
ArrayList<Class1> l2 = new ArrayList<Class1>();

        Iterator iterator1 = l1.iterator();
        boolean repeated = false;

        while (iterator1.hasNext())
        {
            Class1 c1 = (Class1) iterator1.next();
            for (Class1 _c: l2) {
                if(_c.getId() == c1.getId())
                    repeated = true;
            }
            if(!repeated)
                l2.add(c1);
        }

像这样的东西会更好吗?

public static void removeDuplicates(ArrayList<String> list) {
    Arraylist<Object> ar     = new Arraylist<Object>();
    Arraylist<Object> tempAR = new Arraylist<Object>();
    while (list.size()>0){
        ar.add(list(0));
        list.removeall(Collections.singleton(list(0)));
    }
    list.addAll(ar);
}

这应该保持顺序,并且在运行时也不是二次的。

如果您使用的模型类型为List< T>/ArrayList< T>。希望,它能帮到你。

下面是我的代码,没有使用任何其他数据结构,如set或hashmap

for (int i = 0; i < Models.size(); i++){
for (int j = i + 1; j < Models.size(); j++) {       
 if (Models.get(i).getName().equals(Models.get(j).getName())) {    
 Models.remove(j);
   j--;
  }
 }
}

在Java 8中:

List<String> deduped = list.stream().distinct().collect(Collectors.toList());

请注意,列表成员的hashCode-equals契约应该得到尊重,以便过滤正常工作。