简体   繁体   中英

how to compare two array of objects to remove duplicates?

I am working with two array of objects to remove duplicates objects.

I have array1 of Class1.java

String name;
String number;

I added objects like below:

list1.add(new Class1("name1","number1"));
list1.add(new Class1("name2","number2"));
list1.add(new Class1("name3","number3"));
list1.add(new Class1("name4","number4"));

list2.add(new Class1("name1","number1"));
list2.add(new Class1("name5","number2"));
list2.add(new Class1("name6","number3"));
list2.add(new Class1("name2","number4"));

now I want to compare list1 and list 2 in the name basis. How can I remove duplicate elements from list1 after comparing with list 2.

You can remove elements in list1 that exists on list2 using the removeAll method. First you have to override the equals and hashCode methods in your class:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Class1)) return false;

    Class1 class1 = (Class1) o;

    return name.equals(class1.name);
}

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

Then after adding the elements, just use the method removeAll like this:

list1.add(new Class1("name1","number1"));
list1.add(new Class1("name2","number2"));
list1.add(new Class1("name3","number3"));
list1.add(new Class1("name4","number4"));

list2.add(new Class1("name1","number1"));
list2.add(new Class1("name5","number2"));
list2.add(new Class1("name6","number3"));
list2.add(new Class1("name2","number4"));

list1.removeAll(list2);

list1 after removing elements:

[Class1{name='name3'}, Class1{name='name4'}]

EDIT

Another way without overriding equals and hashCode is using the removeIf method (available since java 8):

list1.removeIf(c -> list2.stream()
                    .map(Class1::getName)
                    .anyMatch(n -> n.equals(c.getName())));

Here I'm removing each element on list1 whose name is equal to the name of an element on list2 .

Combine both list into single list and send it below custom function :

HashMap store unique key, Select any field(unique value) from own class and set that field value as key into HashMap and class object as value.

private List<Class1> clearListFromDuplicateFirstName(List<Class1> combineList) {

     Map<String, Class1> cleanMap = new LinkedHashMap<String, Class1>();
     for (int i = 0; i < combineList.size(); i++) {
          cleanMap.put(combineList.get(i).getname(), combineList.get(i));
     }

     return new ArrayList<Class1>(cleanMap.values());;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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