intersection of two arrays java

https‮//:‬www.lautturi.com
intersection of two arrays java

To find the intersection of two arrays in Java, you can use the retainAll method of the List interface. This method modifies the list on which it is called by retaining only the elements that are contained in the specified collection.

Here is an example of how to use retainAll to find the intersection of two arrays:

int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {3, 4, 5, 6, 7};

List<Integer> list1 = new ArrayList<>();
for (int i : array1) {
  list1.add(i);
}

List<Integer> list2 = new ArrayList<>();
for (int i : array2) {
  list2.add(i);
}

list1.retainAll(list2);

int[] intersection = list1.stream().mapToInt(i -> i).toArray();

// Output: [3, 4, 5]

In this example, the two arrays are converted to List objects, and then the retainAll method is called on the first list, passing the second list as an argument. This modifies the first list to contain only the elements that are present in both lists. The resulting list is then converted back to an array using the stream and mapToInt methods.

You can also use the stream and filter methods to find the intersection of two arrays. Here is an example of how to do this:

int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {3, 4, 5, 6, 7};

int[] intersection = Arrays.stream(array1)
  .filter(i -> Arrays.stream(array2).anyMatch(j -> j == i))
  .toArray();

// Output: [3, 4, 5]

In this example, the stream method is used to create a stream of elements from the first array, and the filter method is used to select only the elements that are present in the second array. The resulting stream is then converted back to an array using the toArray method.

For more information on working with arrays in Java, you can refer to the Java documentation or other online resources.

Created Time:2017-11-01 22:29:53  Author:lautturi