Java 8

Java 8 How to get common elements from two lists

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 :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

2 comments

  1. For Common Elements from two lists using java8 filter:
    filter is not using properly.
    Current query – list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList());
    Correct query – list1.stream().filter(item-> list2.contains(item)).collect(Collectors.toList());

Ask a question or leave a comment