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


当前回答

虽然将ArrayList转换为HashSet可以有效地删除重复项,但如果您需要保留插入顺序,我宁愿建议您使用这个变体

// list is some List of Strings
Set<String> s = new LinkedHashSet<>(list);

然后,如果需要返回List引用,可以再次使用转换构造函数。

其他回答

这里有一个不影响列表排序的方法:

ArrayList l1 = new ArrayList();
ArrayList l2 = new ArrayList();

Iterator iterator = l1.iterator();

while (iterator.hasNext()) {
    YourClass o = (YourClass) iterator.next();
    if(!l2.contains(o)) l2.add(o);
}

L1是原始列表,l2是没有重复项的列表 (确保你的类有equals方法,根据你想要代表的相等)

假设我们有一个字符串列表,像这样:

List<String> strList = new ArrayList<>(5);
// insert up to five items to list.        

然后我们可以用多种方式删除重复的元素。

Java 8之前

List<String> deDupStringList = new ArrayList<>(new HashSet<>(strList));

注意:如果我们想保持插入顺序,那么我们需要使用LinkedHashSet来代替HashSet

使用番石榴

List<String> deDupStringList2 = Lists.newArrayList(Sets.newHashSet(strList));

使用Java 8

List<String> deDupStringList3 = strList.stream().distinct().collect(Collectors.toList());

注意:如果我们想在一个特定的列表实现中收集结果,例如LinkedList,那么我们可以修改上面的例子:

List<String> deDupStringList3 = strList.stream().distinct()
                 .collect(Collectors.toCollection(LinkedList::new));

我们也可以在上面的代码中使用parallelStream,但它可能不会带来预期的性能优势。查看这个问题了解更多信息。

以下是一个适用于任何对象的解决方案:

public static <T> List<T> clearDuplicates(List<T> messages,Comparator<T> comparator) {
    List<T> results = new ArrayList<T>();
    for (T m1 : messages) {
        boolean found = false;
        for (T m2 : results) {
            if (comparator.compare(m1,m2)==0) {
                found=true;
                break;
            }
        }
        if (!found) {
            results.add(m1);
        }
    }
    return results;
}

像这样的东西会更好吗?

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);
}

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

@jonathan-stafford的解决方案是可以的。但这并没有保持列表的顺序。

如果你想保留列表的顺序,你必须使用这个:

public static <T> void removeDuplicate(List <T> list) {
Set <T> set = new HashSet <T>();
List <T> newList = new ArrayList <T>();
for (Iterator <T>iter = list.iterator();    iter.hasNext(); ) {
   Object element = iter.next();
   if (set.add((T) element))
      newList.add((T) element);
   }
   list.clear();
   list.addAll(newList);
}

这只是为了完成答案。很好!