Here we will see how to get common elements from two lists we can even say the intersection of two lists using different ways.

Example:

Input:
a = {"1","2","3","4","5"}
b = {"1","2","3"}

Result: 1,2,3

Get Common Elements from two Lists:

retainAll() method from the Collection interface is used to remove the common elements from two different lists.

Common Elements from two lists using retainAll():

List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2,3,4,5));
List<Integer> list2 = new ArrayList<>(Arrays.asList(1,2,3));
list1.retainAll(list2);
System.out.println(list1);

Output:

Terminal
[1, 2, 3]

Common Elements from two lists using distinct():

We even get the common elements from two lists using java 8 stream API distinct() method.

List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2,3,4,5));
List<Integer> list2 = new ArrayList<>(Arrays.asList(1,2,3));

List<Integer> result = list1.stream()
        .distinct()
        .filter(list2::contains)
        .collect(Collectors.toList());

result.forEach(System.out::print);

Output:

Terminal
123

Common Elements from two lists using java8 filter:

Getting common elements from two different lists using java 8 filter condition.

List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2,3,4,5));
List<Integer> list2 = new ArrayList<>(Arrays.asList(1,2,3));

List<Integer> finalList =  list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList());

finalList.stream().forEach(System.out::print);

Output:

Terminal
123

Done!

References:

Happy Learning 🙂