Reputation: 477
I have two custom lists say CompanyList such that
public class CompanyList<E> extends Collection<E> implements List<E> {}
Here I have list of CompanyList such that
public class CompanyMakeVO extends BaseVO {
private static final long serialVersionUID = 1L;
private String name;
public CompanyMakeVO() {
super();
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
// overrides equals
public boolean equals(Object obj) {
if (obj == null || !(obj.getClass() == this.getClass())) {
return false;
}
CompanyMakeVO make = (CompanyMakeVO) obj;
// NAME
String thisName = this.getName();
String thatName = make.getName();
if (null == thisName || null == thatName)
return false;
return thisName.equals(thatName);
}
// hashcode
public int hashCode() {
return getName().hashCode();
}
}
I have two such lists say oldList and newList both have some objects of CompanyMakeVO, each object represents a company name via name attribute. Lets say Old list has 3 objects with name as Audi, BMW and Aston Martin while new list has 5 objects with name as Audi, BMW, Aston Martin, Jaquar and Tesla. The Lists will not have any duplicates items i.e comapny name will not be repeated. I need to find the unique element present in either list and also with the list name and element name. What's the best way to find it out?
Upvotes: 4
Views: 271
Reputation: 1292
For small data sets, lists with a few elements, it is convenient to use List.removeAll()
.
For large data sets, like lists with millions of items, you can use a HashMap
to get those elements.
Since List.removeAll()
will try to compare each item in the first list against all elements in the second list, which is O(NM) complexity. For using HashMap
, it only needs O(N+M), faster than the first one.
Upvotes: 2
Reputation: 22422
You can use removeAll
() method from ArrayList
as given below:
List<CompanyMakeVO> companyMakeVOListOld = new ArrayList<>();
//add your items to the old list
List<CompanyMakeVO> companyMakeVOListNew = new ArrayList<>();
//add your items to new list
//now removeAll duplicate items from new list by passing the old list
companyMakeVOListNew.removeAll(companyMakeVOListOld);
ArrayList - removeAll method API:
public boolean removeAll(Collection c)
Removes from this list all of its elements that are contained in the specified collection.
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#removeAll(java.util.Collection)
Upvotes: 0