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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With