0

I have 2 arraylists with me list1 and list 2. Both of them can have the same custom objects. Say employee class objects, which has 2 attributes i.e. empId and empName.

List1 and List2 can have some equal objects. My objective is to remove the objects which are equal in both arraylist1 and arraylist2 into --> arraylist1.

I have tried the below snippet, however, I am looking for an efficient solution/algorithm in terms of time complexity and space complexity.

list1.removeAll(list1.stream().filter((list2)::contains).collect(Collectors.toList()); 

Is this alright or do we have a better solution to achieve this using java 8? Thanks for your help.

3
  • "remove into" is hard to understand. I think what you mean is that you want replace list1 with the intersection of list1 and list2. So that if list1=[1,2,3,4] and list2=[2,4,9], then at the end, list1=[2,4]. Is that correct? Nov 6, 2018 at 18:47
  • Or do you want list1 to contain the items that aren't in list2? You really need to clarify your question. Nov 6, 2018 at 18:50
  • I want list1 to contain the items that are not in list 2.
    – Hackmaster
    Nov 7, 2018 at 6:13

1 Answer 1

0

You can use removeIf which does a single traversal as:

list1.removeIf(list2::contains);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.