从 java 中的 Arraylist 中的列表中删除重复项

Remove duplicates from a list in an Arraylist in java

我检查了很多例子,但我无法申请我的变量。 我有一个 ArratyList Of 字符串列表。

ArrayList<List<String>> bulkUploadList = new ArrayList<List<String>>();

它看起来像这样:

[id、标题、标签、描述]

[4291483113.0000000000000, Camden, camdentown;london, NoValue]
[4292220054.0000000000000, IMG_2720, NoValue, NoValue]
[4292223824.0000000000000, IMG_2917, london;camdentown, NoValue]
[4292224728.0000000000000, IMG_2945, London;CamdenTown, NoValue]

我想删除那些具有相同标题和相同标签的行。 我不知道如何使用 HashSet,因为我有一个字符串列表的 ArrayList。

不是最佳解决方案,但您可以从这个开始:

    ArrayList<List<String>> bulkUploadList = new ArrayList<List<String>>();
    ArrayList<List<String>> result = new ArrayList<List<String>>();

    HashSet<String> hashSet = new HashSet<>();

    for(List<String> item : bulkUploadList) {
        String title = item.get(1);
        String tags = item.get(2);
        String uniqueString = (title + "#" + tags).trim().toUpperCase();

        if(!hashSet.contains(uniqueString)) {
            result.add(item);
            hashSet.add(uniqueString);
        } else {
            System.out.println("Filtered element " + uniqueString);
        }
    }

正如其中一条评论所建议的那样,您应该为数据创建一个 class,使 class 实现 equals(),然后使用 HashSet 删除重复项。像这样。

class Foo {
String id;
String title;
String tags;
String description;

public boolean equals(Foo this, Foo other) {
   return this.id.equals(other.id) 
      && this.title.equals(other.title)
      && etc.
}

然后您可以使用

删除重复项
 Set<Foo> set = new LinkedHashSet<Foo>(list);

as Set不允许重复,使用equals()方法进行校验。

您应该在此处使用 linkedHashSet,因为您希望保留顺序(根据您在别处发表的评论)。

你还应该实现一个与equals()一致的hashcode()方法。