java

findArrayIntersection()

Parameters: int[] arr1, int[] arr2

two integer arrays for comparison

Returns: int[], common elements between arr1 and arr2

The findArrayIntersection function in Java performs an operation to identify the intersection, or shared elements, in two given arrays. Ideal for getting to grips with array manipulation in Java.

Array Manipulation
Sorting
Looping
Conditionals
Medium dificulty

How to Find Intersection of Two Arrays in Java

Welcome, fellow programmer! This informational piece will guide you through the process of programming a function in Java that finds the intersection of two arrays. This function can be a particularly useful tool in your programming arsenal, as it allows you to identify common elements in different datasets. Let's get started on this interesting journey of exploring the logic behind array intersections.

Step 1: Understanding the problem

The first step in any programming task is to understand what is being asked. In this case, we are tasked with finding the intersection of two arrays in Java, meaning we are trying to find any elements that appear in both arrays. This can be achieved by looping through one array and checking if each element appears in the other array.

java
public List<Integer> findIntersection(int[] array1, int[] array2) {
  List<Integer> intersection = new ArrayList<>();
  for (int i : array1) {
    for (int j : array2) {
      if (i == j) {
        intersection.add(i);
      }
    }
  }
  return intersection;
}

Step 2: Optimising the solution

The above solution works, but it is not very efficient as it has to check each element in the first array against each element in the second array. This gives it a time complexity of O(n^2). We can improve this by using a HashSet, which has a time complexity of O(1) for adding elements and checking if an element is present.

java
public List<Integer> findIntersection(int[] array1, int[] array2) {
  Set<Integer> set = new HashSet<>();
  for (int i : array1) {
    set.add(i);
  }
  List<Integer> intersection = new ArrayList<>();
  for (int j : array2) {
    if (set.contains(j)) {
      intersection.add(j);
    }
  }
  return intersection;
}

Step 3: Removing duplicates

A HashSet cannot contain duplicate elements, so this solution will not work if the arrays can contain duplicates and the resulting intersection should reflect this. To handle this, we can use a HashMap instead, mapping each number to the number of times it appears in the array.

java
public List<Integer> findIntersection(int[] array1, int[] array2) {
  Map<Integer, Integer> map = new HashMap<>();
  for (int i : array1) {
    map.put(i, map.getOrDefault(i, 0) + 1);
  }
  List<Integer> intersection = new ArrayList<>();
  for (int j : array2) {
    if (map.getOrDefault(j, 0) > 1) {
      intersection.add(j);
      map.put(j, map.get(j) - 1);
    }
  }
  return intersection;
}

Step 4: Refactoring the code

Now that we have a working solution, we can make it look a bit cleaner by replacing the for-each loops with the newer stream API.

java
public List<Integer> findIntersection(int[] array1, int[] array2) {
  Map<Integer, Long> map = Arrays.stream(array1).boxed()
      .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
  return Arrays.stream(array2).boxed()
      .filter(i -> map.containsKey(i) && map.get(i) > 1)
      .peek(i -> map.put(i, map.get(i) - 1))
      .collect(Collectors.toList());
}

Step 5: Conclusion

There you have it, a method for finding the intersection of two arrays in Java. It uses the power of Java's collection classes to perform the task efficiently, and it is able to deal with arrays that can contain duplicate elements.

Here's the final form of our function:

java
public class Main {
  public static void main(String[] args) {
    int[] array1 = {1, 2, 2, 3, 4};
    int[] array2 = {2, 2, 3, 5};
    System.out.println(findIntersection(array1, array2)); // prints: [2, 2, 3]
  }

  public static List<Integer> findIntersection(int[] array1, int[] array2) {
    Map<Integer, Long> map = Arrays.stream(array1).boxed()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    return Arrays.stream(array2).boxed()
        .filter(i -> map.containsKey(i) && map.get(i) > 1)
        .peek(i -> map.put(i, map.get(i) - 1))
        .collect(Collectors.toList());
  }
}

Learn function in:

Array Intersection

Finding the common elements between two arrays

Learn more

Mathematical principle

The mathematical principle behind this function involves the concept of sets in mathematics. In particular, the intersection of sets. This refers to all elements that are common in both sets. In this case, each array is considered a set.

Learn more