There are two lists, the task is to print Common elements from java 8.
- First, we take two Arraylist object list1 and list2 with input parameter.
- Here list.stream() is used to enable the Stream API to process the elements within the list.
- Inside filter(list2::contains) method is used to check if the list1 element is present in the specified list2 or not. if the element is present then its return true otherwise false.
- From collect() method, we collect all the common list of integer data.
- Print the Common elements in two lists.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CommonElements {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(23, 45, 67, 80, 21, 98);
List<Integer> list2 = Arrays.asList(12, 67, 43, 78, 80, 23);
List<Integer> commonElement = list1.stream().filter(list2::contains).collect(Collectors.toList());
System.out.println("common elements are :- " + commonElement);
}
}
Output :-
common elements are :- [23, 67, 80]