Gnanam
Gnanam

Reputation: 10923

INTERSECT result of 2 ArrayList containing Integer values

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.

Upvotes: 0

Views: 2543

Answers (3)

Bala
Bala

Reputation: 4547

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

ListUtils.intersection(list1, list2)

Upvotes: 0

DDK
DDK

Reputation: 1038

list1.retainAll(list2)//for intersection

Upvotes: 0

Geert-Jan
Geert-Jan

Reputation: 18895

If you're okay with overwriting result for list1:

list1.retainAll(list2);

otherwise clone/copy list1 first.

Not sure on performance though.

Upvotes: 4

Related Questions