Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from two lists

I have two lists of Strings and am removing duplicates like this:

List<String> list1 = Arrays.asList("1", "2", "3", "4");
List<String> list2 = Arrays.asList("1", "4", "5", "6");
List<String> duplicates = list1.stream().filter(s -> list2.contains(s)).collect(Collectors.toList());
list1.removeAll(duplicates);
list2.removeAll(duplicates);

So the result is:

list1 = 2, 3
list2 = 5, 6

Is there a better way to accomplish this? i.e. with fewer statements.

like image 355
Packs Avatar asked Jun 30 '26 02:06

Packs


1 Answers

You can use removeAll which is defined in Collection interface.

boolean removeAll(Collection<?> c)

Removes all of this collection's elements that are also contained in the specified collection (optional operation). After this call returns, this collection will contain no elements in common with the specified collection.

// init
List<String> sourceList1 = Arrays.asList("1", "2", "3", "4");
List<String> sourceList2 = Arrays.asList("1", "4", "5", "6");

// you need to create duplicate collection, because removeAll modify collection 
List<String> resultList1 = new ArrayList(sourceList1);
List<String> resultList2 = new ArrayList(sourceList2);

//remove duplicates from collections
resultList1.removeAll(sourceList2); // second from first
resultList2.removeAll(sourceList1); // first from second

like image 120
Oleg Poltoratskii Avatar answered Jul 02 '26 16:07

Oleg Poltoratskii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!