【问题标题】:Remove duplicates from a list in an Arraylist in java从java中的Arraylist中的列表中删除重复项
【发布时间】:2016-03-16 02:43:39
【问题描述】:

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

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。

【问题讨论】:

  • 为什么你首先有一个字符串数组列表?创建一个类来保存这些数据。
  • 请您再解释一下,让他们上课是什么意思。这是来自 DB 的选择查询的结果,我将删除重复项并存储在 DB 的另一个表中
  • 为什么要在 Java 中进行重复删除?你有一个 RDBMS 引擎:使用它!
  • 1-我不专业。 2-订单对我来说很重要,基于哪些项目相似以及基于哪个订单我也做不同的事情并为它们制作关系表。3-以防万一,有办法,所以我不知道如何去做吧!
  • 您可以使用“distinct”、“group by”或其他方式删除数据库中的重复项

标签: java arraylist duplicates hashset


【解决方案1】:

不是最好的解决方案,但你可以从这个开始:

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

【讨论】:

  • 我添加了转换为大写和修剪操作,谢谢。我们也可以分别修剪每个参数
  • @EldarBudagov 你好。我有另一个问题。我可以删除那些具有相同标题和标签的行,只保留其中一个。我如何在保留列表中找到哪个 id 对应于哪个删除了一个?
  • 使用HashMap代替HashSet来保留id和data的绑定
【解决方案2】:

按照其中一个 cmets 的建议,您应该为数据创建一个类,使该类实现 equals(),然后使用 HashSet 删除 dups。像这样。

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.
}

然后您可以使用

删除 dup
 Set<Foo> set = new LinkedHashSet<Foo>(list);

as Sets 不允许重复,使用 equals() 方法进行检查。

您应该在此处使用linkedHashSet,因为您想保留顺序(根据您在其他地方发表的评论)。

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

【讨论】:

  • 感谢您的写作,我也将使用它来学习如何使用它:)
猜你喜欢
  • 2011-01-26
  • 2012-08-25
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 2015-12-12
  • 1970-01-01
相关资源
最近更新 更多