Java 8 – How to find common & uncommon elements from 2 Lists ?

In this article, we will discuss how to find and print common & uncommon elements from 2 Lists (or ArrayList)

There are different ways to find common & uncommon elements from 2 List objects but here we will use Streams API introduced in Java 1.8 version

Nowadays, this become one of the favorite interview question for the Interviewer at the fresher & intermediate levels

1. Find Uncommon elements :

Few assumption before proceeding further,

  • First List contains more elements when comparing with second List
  • Second list is subset of First List

FindUncommonElementsFrom2ListUsingJava8Stream.java

package in.bench.resources.common.elements;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FindUncommonElementsFrom2ListUsingJava8Stream {

	public static void main(String[] args) {

		// first & second List
		List<String> nameList1 = Arrays.asList("Ram", "Sam", "Sundar", "Shaz", "Ankit");
		List<String> nameList2 = Arrays.asList("Ram", "Sam", "Shaz");


		// find uncommon elements & store in new List
		List<String> uncommonNames = nameList1
				.stream()
				.filter(name -> !nameList2.contains(name))
				.collect(Collectors.toList());


		// print to console
		System.out.print(uncommonNames);
	}
}

Output :

[Sundar, Ankit]

2. Find Common elements :

We will use the same example and try to find common elements from both the ArrayList

FindCommonElementsFrom2ListUsingJava8Stream.java

package in.bench.resources.common.elements;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FindCommonElementsFrom2ListUsingJava8Stream {

	public static void main(String[] args) {

		// first & second List
		List<String> nameList1 = Arrays.asList("Ram", "Sam", "Sundar", "Shaz", "Ankit");
		List<String> nameList2 = Arrays.asList("Ram", "Sam", "Shaz");


		// find common elements & store in new List
		List<String> commonNames = nameList1
				.stream()
				.filter(name -> nameList2.contains(name))
				.collect(Collectors.toList());


		// print to console
		System.out.print(commonNames);
	}
}

Output :

[Ram, Sam, Shaz]

Related Articles :

References:

Happy Coding !!
Happy Learning !!

Java 8 - How to Reverse a String in place ?
Java 8 – How to sort HashMap by its Values first and then by its Keys ?