-2

Android 4.4

suppose I has 2 lists. I need to return sublist of items in first list that not contain in second list.

E.g:

[1,2,3,4,5] - [1,2,3,4,5] -> return []

[1,2,3,4,5] - [1,22,3,4,5] -> return [2]

[1,2,3,4,5] - [6,7,8,9,10] -> return [1,2,3,4,5]

[1,2,3,4,5] - [1,2,3,4,5,6] -> return []

[1,2,3,4,5] - [6,7,8,9,2] -> return [1,3,4,5]

How I can do this simple? I can write custom java method to do this. But maybe already exist any good solution.

I need this because I need to remove all items from first list that not contain in second list.

Thanks.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Alexei
  • 14,350
  • 37
  • 121
  • 240

1 Answers1

1

You can use List.removeAll(Collection) :

List<Integer> listFirst = ...;
List<Integer> listSecond = ...;

List<Integer> listThird = new ArrayList<>(listFirst);// use of 3rd list to keep the 2 others
listThird.removeAll(listSecond);
azro
  • 53,056
  • 7
  • 34
  • 70