How to get the intersection of two collections in java

With collections it is very easy to get the intersection of two collections. Here is a simple example which creates two lists and then gets the intersection of two lists. We would be using retainAll(Collection<?> c) One thing that you should be aware of is that the list on which retainAll method is invoked will contain only the intersection elements. So all the other elements of the list will be removed. If you don’t want that behavior, it is better to create a new list. See the second example.

IntersectionOfTwoCollections.java

package com.programtalk.beginner.tutorial;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class IntersectionOfTwoCollections {
	public static void main(String[] args) {
		// doing this to make the list mutable
		List<Integer> a = new ArrayList<>(Arrays.asList(1,2, 3, 9));
		List<Integer> b = new ArrayList<>(Arrays.asList(1,2, 3, 4, 5));
		System.out.println("b before intersection :" + b);
		System.out.println("list to be intersected with :" + a);
		b.retainAll(a);
		System.out.println("b after intersection :" + b);
	}
}

And the output is:

b before intersection :[1, 2, 3, 4, 5]
list to be intersected with :[1, 2, 3, 9]
b after intersection :[1, 2, 3]

Example with intermediate List

package com.programtalk.beginner.tutorial;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class IntersectionOfTwoCollections {
	public static void main(String[] args) {
		// doing this to make the list mutable
		List<Integer> a = new ArrayList<>(Arrays.asList(1,2, 3, 9));
		List<Integer> b = new ArrayList<>(Arrays.asList(1,2, 3, 4, 5));
		
		List<Integer> intermediateList = new ArrayList<>(b);
		System.out.println("b before intersection :" + b);
		System.out.println("intermediateList before intersection :" + intermediateList);
		System.out.println("list to be intersected with :" + a);
		intermediateList.retainAll(a);
		System.out.println("\nb after intersection :" + b);
		System.out.println("intermediateList after intersection :" + intermediateList);
		System.out.println("a list still contains same elements :" + a);
	}
}

output:

b before intersection :[1, 2, 3, 4, 5]
intermediateList before intersection :[1, 2, 3, 4, 5]
list to be intersected with :[1, 2, 3, 9]

b after intersection :[1, 2, 3, 4, 5]
intermediateList after intersection :[1, 2, 3]
a list still contains same elements :[1, 2, 3, 9]

References

https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/List.html#retainAll(java.util.Collection)

Like this post? Don’t forget to share it!

Leave a Reply

Your email address will not be published. Required fields are marked *