-2

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 ?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
JavaBuilder
  • 149
  • 9
  • Please provide more information because very few details.. Which is the relation of 2 arrays? Is one to one or? Entries are on the same index or? – victor.chicu Jun 19 '20 at 15:00
  • 3
    Use `retainAll` to get common element and use `removeAll` to remove them from each list https://stackoverflow.com/a/5943335/4207306, https://stackoverflow.com/a/16634482/4207306 – Eklavya Jun 19 '20 at 15:01

3 Answers3

0

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);
}
ognjenkl
  • 1,407
  • 15
  • 11
0
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());
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Jun 19 '20 at 20:53
0

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]

WJS
  • 36,363
  • 4
  • 24
  • 39