0

I am trying to get the intersection between Two List in JAVA, Please find the List below

LIST 1:

List<EligViewEventSubject> list1=  new ArrayList<>();

list1=   [EligViewEventSubject [event=EOD, subjectTypeCd=HOLDINGS, region=IA], EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]

LIST 2:

List<EligViewEventSubject> list2=  new ArrayList<>();

list2 = [EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]

The Result for the above should be Like below

List<EligViewEventSubject> resultList =  new ArrayList<>();

resultList = [EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]

In short i want the Matching ones alone(intersection)

I have tried the below:

List<EligViewEventSubject> unionList = new ArrayList<>(list1);
        unionList.addAll(list2);

List<EligViewEventSubject> intersectionList = new ArrayList<>(list1);
        intersectionList.retainAll(list2);

Union List I get as:

[EligViewEventSubject [event=EOD, subjectTypeCd=HOLDINGS, region=IA], EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA], EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]

Intersection is []

Please share your thoughts on this.

devaerial
  • 2,069
  • 3
  • 19
  • 33

1 Answers1

0

Please reference this question, as this has already been answered. Intersection and union of ArrayLists in Java

To summarize, you can get the intersection of two arraylists in java as such:

public <T> List<T> intersection(List<T> list1, List<T> list2) {
    List<T> list = new ArrayList<T>(); 

    for (T t : list1){
       if(list2.contains(t)){
           list.add(t); 
       } 
    } 

   return list; 
}