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 sub–set 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 :
- Java features version-wise
- Java – How to print an Arrays elements ?
- Java – String join() method
- Java 8 – Connect to MS Access database using JDBC
- Java 8 – How to check whether a number exists in an Arrays or List or Stream ?
- Java 8 – How to find even/odd number from a range of numbers ?
- Java 8 – How to find common & uncommon elements from 2 Lists ?
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
- https://docs.oracle.com/javase/8/docs/api/java/util/List.html
Happy Coding !!
Happy Learning !!