I have two arrayList
that can contain 0 or many int
and I need to create a new arrayList
from these two with values that are in both. In this case [4,23]
Example
arrayList1 [3 ,4 ,7,23,12]
arrayList2 [13,4,17,23,15]
In this example I need a new arrayList
containing [4,23]
Is there an easy way to do it with .contains()
or some similar method. Or should I
loop through both list and check for equality and create the new list ?
Knowing that one or the other arrayList
can be empty.
Thank you
This would be more efficient with sets, but even just with lists, it's simple to use retainAll
:
// Start by copying arrayList1
List<Integer> result = new ArrayList<Integer>(arrayList1);
result.retainAll(arrayList2);
That's assuming you don't want to modify arrayList1
. If you don't mind about that, you can skip the first step:
arrayList1.retainAll(arrayList2);
You should strongly consider using sets if that's what you're logically talking about though.
See more on this question at Stackoverflow