0

Hi I have two list example List list1 and LIST List list2

How to get common data ? Data is there in first list only? Data is there in second list only?

Since i am using List is i need to ovveride equals and hashcode method?

Please could you help with sample example.

user1921479
  • 255
  • 2
  • 6
  • 13
  • Show us what you have tried so far, your code. – ForInfinity Mar 21 '17 at 14:28
  • Possible duplicate of [Java Compare Two Lists](http://stackoverflow.com/questions/2762093/java-compare-two-lists) – szab.kel Mar 21 '17 at 14:30
  • 1
    Do you care about ordering? Are lists [A,B] and [B,A] different? How many differences are there between [B,C] and [A,B,C]? If your answer is 'no' and 'only A' then you are interested in difference between Sets, not lists, which is considerably easier - please rephrase your question in such case. – Artur Biesiadowski Mar 21 '17 at 14:30

1 Answers1

1
ArrayList onlyInList1 = new ArrayList(list1);
onlyInList1.removeAll(list2);

ArrayList onlyInList2 = new ArrayList(list2)
list2.removeAll(list1);

ArrayList inBoth = new ArrayList(list1)
inBoth.retainAll(list2);
slass100
  • 66
  • 4
  • If list1 contains list beans means is i need to override has code and equal method in bean? – user1921479 Mar 21 '17 at 16:15
  • If list1 contains bean1, list2 contains bean2, and bean1 and bean2 do not reference the same object, then yes you should override the "equals()" method. You should also override "hashcode()" to something reasonable. – slass100 Mar 22 '17 at 20:03