#JavaInspires
Hi Guys,
Welcome to Java Inspires.
In this post, we will see How to get Common elements from two lists using Stream API filter().
Here, we will create two string lists with some common elements and will get common elements list by using filter method from stream api.
Java8Example.java
package com.javainspires.java8example; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * * @author Java Inspires * */ public class Java8Example { public static void main(String[] args) { // lets create two list with some common elements List<String> list1 = Arrays.asList("Arun", "Kent", "Rahul", "Mathew", "Clark"); System.out.println("List 1 : "+list1); List<String> list2 = Arrays.asList("Kent", "Rahul", "Robert", "Alison"); System.out.println("List 2 : "+list2); // use distinct from stream api // convert list1 to stream Stream<String> stream1 = list1.stream(); // use distinct from stream and filter Stream<String> stream11 = stream1.filter(list2::contains); // convert stream to list List<String> commonList = stream11.collect(Collectors.toList()); System.out.println(); System.out.println("Common Elements : "+commonList); } }
List 1 : [Arun, Kent, Rahul, Mathew, Clark] List 2 : [Kent, Rahul, Robert, Alison] Common Elements : [Kent, Rahul]