从ArrayList中删除重复项

26

我有一个自定义对象的ArrayList。我想要删除重复的条目。

这些对象有三个字段:title, subtitleid。如果一个副标题出现多次,我只需要具有该副标题的第一项(忽略具有该副标题的其余对象)。


2
如果您不想要重复项,一开始使用Set会更简单。 - Peter Lawrey
我使用了TreeSet并在树中添加了子标题。如果add方法返回true,我会将对象添加到另一个ArrayList中。 - Bytecode
14个回答

0
List<YourObject> all = ******** // this is the object that you have already  and filled it.
List<YourObject> noRepeat= new ArrayList<YourObject>();

for (YourObject al: all) {
    boolean isPresent = false;
    // check if the current objects subtitle already exists in noRepeat
    for (YourObject nr : noRepeat) {
        if (nr.getName().equals(al.getName()) {
            isFound = true;//yes we have already
            break;
        }
    }

    if (!isPresent)
        noRepeat.add(al); // we are adding if we don't have already
}

创建一个新的ArrayList对象,类型与旧的ArrayList相同。 逐一将所有旧ArrayList的元素添加到这个新的ArrayList对象中,但在添加每个对象之前,检查新的ArrayList中是否有具有相同副标题的对象。如果新的ArrayList包含这样的副标题,则不添加它。否则,添加它。

0
在Java 8中,你也可以像这样做:
yourList.stream().collect(
     Collectors.toMap(
         obj -> obj.getSubtitle(),
         Function.identity(), 
         (o1,o2) -> o1))
    .values();

关键是收集流到映射并提供键冲突解析器lambda ((o1,o2) -> o1),它总是返回其第一个参数。 结果是一个Collection,而不是List,但您可以轻松地将其转换为List:

new ArrayList(resultCollection);

0

另一种使用Java 8流的方法,你也可以做得很酷:

List<Customer> CustomerLists;
List<Customer> unique = CustomerLists.stream().collect(collectingAndThen(
        toCollection(() -> new TreeSet<>(comparingLong(Customer::getId))),
        ArrayList::new));

0

解决方案取决于具体情况。

如果数据量不大,则使用Set Set<T> unique = new HashSet<>(yourList);(如果您关心顺序,请使用LinkedHashSet)。它会创建一个新的集合,但通常不是问题。

当您想要修改现有列表并且不想/无法创建新集合时,可以像这样删除重复项:

List<Integer> numbers =
    new ArrayList<>(asList(1, 1, 2, 1, 2, 3, 5));

System.out.println("Numbers: " + numbers);
ListIterator<Integer> it = numbers.listIterator();
while (it.hasNext()) {
    int i = it.nextIndex();
    Integer current = it.next();
    for (int j = 0; j < i; ++j) {
        if (current.equals(numbers.get(j))) {
            it.remove();
            break;
        }
    }
}
System.out.println("Unique: " + numbers);

虽然它的时间复杂度为O(n^2),但它确实有效。类似的实现方法,但更简单的是当列表已排序时 - 时间复杂度为O(n)。这两种实现方法都在Farenda上有解释:从列表中删除重复项 - 各种实现


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接