Java Array Intersect intersect(String[] list1, String[] list2)

Here you can find the source of intersect(String[] list1, String[] list2)

Description

Returns intersections of two list.

License

Open Source License

Declaration

public static String[] intersect(String[] list1, String[] list2) 

Method Source Code

//package com.java2s;
/*//w  w  w  .  j a  v a2 s .  com
 * StringUtil.java
 *
 * Copyright (c) 2005-2009 Andrew Krizhanovsky <andrew.krizhanovsky at gmail.com>
 * Distributed under GNU Public License.
 */

import java.util.Map;
import java.util.HashMap;

public class Main {
    /** Returns intersections of two list.
     * Return null if input String[] is null.
     */
    public static String[] intersect(String[] list1, String[] list2) {
        if (null == list1 || 0 == list1.length || null == list2 || 0 == list2.length) {
            return null;
        }

        Map<String, Boolean> map1 = new HashMap<String, Boolean>();

        for (String s : list1) {
            map1.put(s, false);
        }

        int counter = 0;
        for (String s : list2) {
            if (map1.containsKey(s)) {
                //map1.put(s, true);
                counter++;
            }
        }

        String[] res = new String[counter];
        counter = 0;
        for (String s : list2) {
            if (map1.containsKey(s)) {
                res[counter++] = s;
            }
        }

        return res;
    }
}

Related

  1. hasIntersection(String a1[], String a2[], int mode)
  2. intersect(boolean[] mask, int[] examples, boolean[] intersection)
  3. intersect(int[] sorted1, int[] sorted2)
  4. intersect(int[]... arrays)
  5. intersect(String[] arr1, String[] arr2)
  6. intersect(T[] a, T[] b)
  7. intersect(T[] a, T[] b)
  8. intersectArrays(int[] a, int[] b)
  9. intersectArrays(int[] targetArray, int[] selfArray)