简体   繁体   English

合并没有重复项的Model元素的ArrayList

[英]Merging ArrayList of Model elements without duplicates

Hi I have two array list List l1 and List l2, Name,age,sex,uniqID,marks are the data inside the lists. 嗨,我有两个数组列表列表l1和列表l2,名称,年龄,性别,uniqID,标记是列表中的数据。 I want to join l1 and l2 without duplicates.uniqID is unique for each student. 我想加入l1和l2而没有重复项。uniqID对于每个学生都是唯一的。 I have been looping through all the elements and comparing each and every element. 我一直在遍历所有元素并比较每个元素。 But My list would have around 20k items so the looping is taking too much time. 但是我的清单中大约有2万个项目,因此循环需要太多时间。 I have tried all the answers from this post nothing worked for me. 我已经尝试过此帖子中的所有答案,但对我没有用。 Any suggestions.? 有什么建议么。?

Simple example: 简单的例子:

public class Person{
    int id;
    String name;
    //fields, getter, setter, constructor omited....

    @Override
    public boolean equals(Object o){
        if (!(o instanceof Person)){
            //implicit null check
            return false;
        }
        return this.id==((Person)o).id;
    }

    @Override
    public int hashCode(){
        return this.id;
    } 
}

The class Person does implement equals and hashCode now. Person类现在确实实现了equals和hashCode。 equals is used by java for deciding if an object is a duplicate of another object. Java使用equals来确定一个对象是否与另一个对象重复。 hashCode is not necessary per se, but it is suggested to override hashCode and equals together. hashCode本身不是必需的,但建议重写hashCode并使其equals

If both methods are implemented, you can simply use the build-in methods and datastructures in java: 如果两种方法都实现,则可以简单地使用java中的内置方法和数据结构:

With lists: 带有列表:

List<Person> listA = new ArrayList<>();
List<Person> listB = new ArrayList<>();
// filling the lists omitted
List<Person> mergedList=new ArrayList<>();
mergedList.addAll(listA);
mergedList.removeAll(listB);
mergedList.addAll(listB);

Or with sets: 或搭配:

List<Person> listA = new ArrayList<>();
List<Person> listB = new ArrayList<>();
// filling the lists omitted
Set<Person> mergedSet=new HashSet<>();
mergedSet.addAll(listA);
mergedSet.addAll(listB);

You can combine both the arraylist and pass it to HashSet object As Set does not contain duplicates you can do following 您可以组合两个arraylist并将其传递给HashSet对象,因为Set不包含重复项,您可以执行以下操作

ArrayList<String> a=new ArrayList<String>();
ArrayList<String> b=new ArrayList<String>();

b.addAll(a);

If you want to retain the order of elements use LinkedHashSet 如果要保留元素的顺序,请使用LinkedHashSet

LinkedHashSet<String> result=new LinkedHashSet<String>(b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM