I want to remove common entries from 2 ArrayList
:
A = [1,2,3,5]
B = [1,2,3,7]
O/P :
A = [5]
B = [7]
Is there any java8 function for above ? How to handle it efficiently ?
I want to remove common entries from 2 ArrayList
:
A = [1,2,3,5]
B = [1,2,3,7]
O/P :
A = [5]
B = [7]
Is there any java8 function for above ? How to handle it efficiently ?
Maybe this is efficient enough:
public void removeCommonElements(List<Integer> list1, List<Integer> list2) {
List<Integer> list3 = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
list1.removeAll(list3);
list2.removeAll(list3);
}
List<Integer> list3 = list1.stream()
.filter(var -> {return !list2.contains(var);})
.collect(Collectors.toList());
List<Integer> list4 = list2.stream()
.filter(var -> {return !list1.contains(var);})
.collect(Collectors.toList());
As suggested, you can do this.
List<Integer> list1 = new ArrayList<>(List.of(1,2,3,5));
List<Integer> list2 = new ArrayList<>(List.of(1,2,3,7));
List<Integer> commonElements = new ArrayList<>(list1);
commonElements.retainAll(list2);
list1.removeAll(commonElements);
list2.removeAll(commonElements);
System.out.println(list1);
System.out.println(list2);
Prints
[5]
[7]