0

I've two ArrayList both containing Integer values. My objective is to get identical/common/duplicate values comparing these 2 list. In other words (in SQL parlance), I need the INTERSECT result of two lists, that is, values that appear in both list.

Example:

ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(100);
list1.add(200);
list1.add(300);
list1.add(400);
list1.add(500);

ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(300);
list2.add(600);

One kind of implementation/solution I could think along is looping one of the list something like:

ArrayList<Integer> intersectList = new ArrayList<Integer>();

for (Integer intValue : list1) 
{
    if(list2.contains(intValue))
        intersectList.add(intValue);
}

In this case, intersectList would contain only 1 Integer item being added, that is 300, which appears in both list.

My question is, are there any better/fastest/efficient way of implementing this logic? Any options available in Apache Commons library?. Any other ideas/suggestions/comments are appreciated.

NOTE: For illustration purpose, I've just shown here 5 items and 2 items being added into the list. In my real-time implementation, there will be more than 1000 elements in each list. Therefore, performance is also a key factor to be considered.

Gnanam
  • 10,613
  • 19
  • 54
  • 72
  • possible duplicate of http://stackoverflow.com/questions/5283047/intersection-union-of-arraylists-in-java – DDK Jul 13 '12 at 10:32

3 Answers3

4

If you're okay with overwriting result for list1:

list1.retainAll(list2);

otherwise clone/copy list1 first.

Not sure on performance though.

Geert-Jan
  • 18,623
  • 16
  • 75
  • 137
0
list1.retainAll(list2)//for intersection
DDK
  • 1,032
  • 18
  • 39
0

Use ListUtils from org.apache.commons.collections if you do not want to modify existing list.

ListUtils.intersection(list1, list2)

Bala
  • 4,427
  • 6
  • 26
  • 29