In this tutorial, we will see “How to find common elements of two arrays using Java 8 Streams?”find common elements of two arrays using Java 8 Stream
Java 8 – How to find common elements in two arrays using Streams? Share on X
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | /** * Find the common elements of two arrays in Java 8 * @author Deepak Verma * */ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Find_common_elements_of_two_arrays_using_Java8 { public static void main(String[] args) { int[] arrayOfIntegers1 = {1, 2, 3, 4, 5}; int[] arrayOfIntegers2 = {4, 5, 6, 7, 8}; List<Integer> listOfInteger1 = Arrays.stream(arrayOfIntegers1) .boxed() .collect(Collectors.toList()); List<Integer> listOfInteger2 = Arrays.stream(arrayOfIntegers2) .boxed() .collect(Collectors.toList()); List<Integer> commonElements = listOfInteger1.stream() .filter(listOfInteger2::contains) .collect(Collectors.toList()); System.out.println("Array1: " +Arrays.toString(arrayOfIntegers1)); System.out.println("Array2: " +Arrays.toString(arrayOfIntegers2)); System.out.println("Common elements in both arrays: " + commonElements); } } |
Output:
1 2 3 | Array1: [1, 2, 3, 4, 5] Array2: [4, 5, 6, 7, 8] Common elements in both arrays: [4, 5] |
find common elements of two arrays using Java 8 Streams
As per above example, It first converts the arrays into lists using Arrays.stream()
, then converts the primitive int arrays into integer objects using boxed()
. After that, The resulting lists are filtered using the filter()
method, which only keeps the elements that are also present in listOfInteger2
using the contains
predicate. At last, the common elements are collected into a new list using the collect()
method.
Java 8 – How to find common elements in two arrays using Streams? Share on X
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: