Packs
Packs

Reputation: 43

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.

Upvotes: 4

Views: 3372

Answers (2)

Oleg Poltoratskii
Oleg Poltoratskii

Reputation: 806

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

Upvotes: 1

Przemysław Moskal
Przemysław Moskal

Reputation: 3609

One of the possibilities worth considering is to create Set<String> and add these lists to it. Set allows adding only unique values to itself, it prevents adding duplicates.

The first way to use Set: Create a Set containing an intersection of both lists. Adding to new, getting rid of duplicates lists is taking place only if you checked that every object of the source is not present in previously created Set of duplicates.

Second way (only if your lists doesn't care about holding duplicates itself - for example in the first you have two times the same value existing): Create a Set for the first and for the second list, and add these lists to them and after that check for duplicates.

As I mentioned in comments I could misunderstood question and looked for "another", not for "more efficient" way of achieving what you're asking for, but maybe it could actually be helpful nonetheless.

Upvotes: 0

Related Questions