Sunday, 2 August 2015

Find intersection of two arrays

Given two arrays A and B, find common elements in both A and B.
You can solve this problem using HashSet easily. First insert one Array elements into HashSet. Next traverse second array and check whether element is in HashSet or not. If elements present in HashSet, then it is common to both arrays.
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

public class ArrayIntersection {

 public static Set<Integer> getIntersection(List<Integer> a, List<Integer> b) {
  Set<Integer> result = new HashSet<>();

  Objects.nonNull(a);
  Objects.nonNull(b);

  if (a.size() == 0 || b.size() == 0)
   return result;

  Set<Integer> set = new HashSet<>(a);

  for (int i : b) {
   if (set.contains(i))
    result.add(i);
  }

  return result;
 }
}

Following is the junit test case for above program.


import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.junit.Test;

import recursion.ArrayIntersection;

public class ArrayIntersectionTest {

 @Test
 public void test1() {
  List<Integer> arr1 = Arrays.asList(1, 2, 3, 4, 5, 6);
  List<Integer> arr2 = Arrays.asList(3, 4, 5, 6, 7, 8, 9, 10, 3);
  Set<Integer> expected = new HashSet<>(Arrays.asList(3, 4, 5, 6));

  Set<Integer> result = ArrayIntersection.getIntersection(arr1, arr2);
  assertTrue(expected.equals(result));

 }
}



No comments:

Post a Comment