[英]Remove duplicates from a list in an Arraylist in java
I checked many examples but i could not applied for my variables. 我检查了很多示例,但无法申请变量。 I have a ArratyList Of lists of Strings.
我有一个ArratyList的字符串列表。
ArrayList<List<String>> bulkUploadList = new ArrayList<List<String>>();
and it's look like this: 看起来像这样:
[id, title, tags, descriptions] [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]
I want to remove those rows which have the same titles and the same tags. 我想删除那些标题和标签相同的行。 I do not know how work with HashSet since I have a ArrayList of List of Strings.
我不知道如何使用HashSet,因为我有一个字符串列表的ArrayList。
Not best solution, but you can start with this: 不是最佳解决方案,但是您可以从以下开始:
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);
}
}
As suggested in one of the comments, you should create a class for the data, make that class implement equals(), and then use HashSet to remove dups. 如其中一项注释中所建议,您应该为数据创建一个类,使该类实现equals(),然后使用HashSet删除重复项。 Like this.
像这样。
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.
}
then you can remove dups with 然后您可以用
Set<Foo> set = new LinkedHashSet<Foo>(list);
as Sets do not allow duplication, and the equals() method is used to check. 因为Set不允许重复,所以equals()方法用于检查。
You should use a linkedHashSet here because you want to preserve the order (according to a comment you made on elsewhere). 您应在此处使用linkedHashSet,因为您想保留订单(根据您在其他地方发表的评论)。
You should also implement a hashcode() method consistent with equals(). 您还应该实现与equals()一致的hashcode()方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.