best way to find an extra item from two lists

advertisements

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?


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.