简体   繁体   中英

Union of two lists containing objects

I have two list

ListA<TestData> listA = new ArrayList<TestData>()
ListB<TestData> listB = new ArrayList<TestData>() 

both contain object of type TestData and TestData contain these variables.

TestData {
    String status;
    String billType;
} 

I want union of the two lists.

ListA = ["ACTV","S"],["DISC","E"];

ListB = ["ACTV","V"],["DISC","E"],["DISC","S"];

UpdatedList = ["ACTV","S"],["DISC","E"],["ACTV","V"],["DISC","S"];

I tried by checking below condition but it is not working.

for (TestData myData : ListA) {
        if(!ListB.contains(myData))
            return true;
    }

Can you please let me know the correct and efficient way to merge the list. or this can be achievable my using some other collection.

You can use a Set and let TestData override equals and hashCode to avoid the duplicates.

TestData {
   String status;
   String billType;

   public boolean equals(Object obj) { 
      if (obj == null || !(obj instanceof Testdata)) return false;
      TestData other = (TestData) obj;

      return status.equals(other.getStatus()) && billType.equals(other.getBillType())
   }

   public int hashCode() {
      int hashcode = 31;
      hashcode += 31 * status.length();
      hashcode += 31 * billType.length();
      return hashcode;
   }
}

and then

Set<TestData> data = new HashSet<>();
data.addAll(listA);
data.addAll(listB);

If you want a sorted TreeSet then implement Comparable instead where you compare in a similar way as the equals method.

You should override equals() method to work with contains() method. https://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains%28java.lang.Object%29

You could do override equals() and hashCode() method in your class and then put all the lists to Set.

Set<TestData> uniqueElements = new HashSet<>();

uniqueElements.addAll(listA);
uniqueElements.addAll(listB);

You can use:

 ListA.addAll(ListB);

This adds all elements on Collection B to A. But List is an interface that allows repeated values.

If you want to ensure not having repeated items you must Overwrite equals method on your TestData class and use Sets (like HashSet) instead of Lists.

Off topic, in Java, variable names start in lowercase, see javacode conventions: http://www.oracle.com/technetwork/java/codeconvtoc-136057.html

You can also use apache commons collections if you are at liberty to use external library

ListUtils.union(listA , listB);

https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#union(java.lang.Iterable,%20java.lang.Iterable)

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