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


当前回答

在Java 8中:

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

请注意,列表成员的hashCode-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,但它可能不会带来预期的性能优势。查看这个问题了解更多信息。

如果不希望集合中有重复项,则应该考虑为什么要使用允许重复项的集合。删除重复元素最简单的方法是将内容添加到Set(不允许重复),然后将Set添加回ArrayList:

Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);

当然,这破坏了数组列表中元素的顺序。

如果你不想重复,使用Set而不是List。要将List转换为Set,可以使用以下代码:

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

如果确实有必要,可以使用相同的结构将Set转换回List。

科特林

val list = listOf('a', 'A', 'b', 'B', 'A', 'a')
println(list.distinct()) // [a, A, b, B]
println(list.distinctBy { it.uppercaseChar() }) // [a, b]

从这里kotlinlang

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

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