I need to compare two ArrayList (they are not necessarily equal size) and create a new ArrayList that contains all the common elements of list1 and list2. Is there a more efficient way of doing this than comparing all the elements of list1 to all the elements of list2?
Asked
Active
Viewed 130 times
-3
-
Also, what are your rules for duplicates? I.E. if list1 contains `[a,b,c]` and list2 contains `[a,a,b]` what would list3 contain? – aruisdante Mar 03 '15 at 17:59
-
I've literally just been taking one element of list1 and comparing it to every elements of list2, and then adding it to the commonList if there's a match. @Batty – Rachel Mar 03 '15 at 18:00
-
@aruisdante, the question made no mention of duplicates so I assume the common list would simply contain it only once – Rachel Mar 03 '15 at 18:00
2 Answers
0
I would say for optimal efficiency just loop over the smaller of the two lists and use the contains method when accessing the longer list.
for(int i = 0; i < listA.length(); i++) {
if(listB.contains(listA.get(i)) {
commonList.add(listA.get(i);
}
}

Ryan D
- 1,023
- 11
- 16
-
There are definitely non *O(n^2)* ways to do this, especially if duplicates don't need to be accounted for and the output list doesn't need to be stable (same order as input lists). – aruisdante Mar 03 '15 at 18:07
0
You could you Apache Commons Collections to do this. What you are looking for is the CollectionUtils.intersection(Iterable a, Iterable b) method.

Robert Niestroj
- 15,299
- 14
- 76
- 119