Java Array Intersect intersect(T[] a, T[] b)

Here you can find the source of intersect(T[] a, T[] b)

Description

Create an intersection of two arrays, removing null values and duplicates

License

Open Source License

Parameter

Parameter Description
a the first array
b the second array

Return

the intersection

Declaration

public static <T> T[] intersect(T[] a, T[] b) 

Method Source Code

//package com.java2s;

import java.util.*;

public class Main {
    /**/*from  ww w  .ja v  a2s .co  m*/
     * Create an intersection of two arrays, removing null values and duplicates
     *
     * @param a the first array
     * @param b the second array
     * @return the intersection
     */
    public static <T> T[] intersect(T[] a, T[] b) {

        ArrayList<T> l = new ArrayList<T>();

        for (int i = 0; i < a.length; i++) {
            if (a[i] == null)
                continue;
            for (int j = 0; j < b.length; j++) {
                if (b[j] == null)
                    continue;
                if (a[i].equals(b[j])) {
                    if (!l.contains(a[i]))
                        l.add(a[i]);
                    break;
                }
            }
        }

        T[] t = Arrays.<T>copyOf(a, l.size());
        for (int i = 0; i < t.length; i++)
            t[i] = l.get(i);

        return t;
    }

    /**
     * Determine whether the array contains the given element
     *
     * @param a the array
     * @param e the element
     * @return true if the element is in the array
     */
    public static <T> boolean contains(T[] a, T e) {

        if (a == null)
            return false;

        for (int i = 0; i < a.length; i++) {
            if (a[i] == e)
                return true;
            if (e != null && e.equals(a[i]))
                return true;
        }

        return false;
    }
}

Related

  1. intersect(int[] sorted1, int[] sorted2)
  2. intersect(int[]... arrays)
  3. intersect(String[] arr1, String[] arr2)
  4. intersect(String[] list1, String[] list2)
  5. intersect(T[] a, T[] b)
  6. intersectArrays(int[] a, int[] b)
  7. intersectArrays(int[] targetArray, int[] selfArray)
  8. intersection(final long[] array1, final long[] array2)
  9. intersection(int[] array1, int[] array2)