Java ArrayList Intersect intersection(ArrayList List1, ArrayList List2)

Here you can find the source of intersection(ArrayList List1, ArrayList List2)

Description

Returns the intersection of two lists passed to it.

License

Open Source License

Parameter

Parameter Description
List1 as an ArrayList
List2 as an ArrayList

Return

List

Declaration

public static ArrayList<Integer> intersection(ArrayList<Integer> List1, ArrayList<Integer> List2) 

Method Source Code

//package com.java2s;
/**/* www  .  j  a  va 2  s.co  m*/
 * 
 * A class that has misc useful functions mostly used for debugging.
 * 
 * @author Alok Dhamanaskar (alokd@uga.edu)
 * @see LICENSE (MIT style license file). The class provides
 * 
 */

import java.util.ArrayList;
import java.util.Set;

public class Main {
    /**
     * Returns the intersection of two lists passed to it.
     *
     * @param List1 as an ArrayList
     * @param List2 as an ArrayList
     * @return List
     */
    public static ArrayList<Integer> intersection(ArrayList<Integer> List1, ArrayList<Integer> List2) {
        ArrayList<Integer> intersection = new ArrayList<Integer>();
        if (List1 != null && List2 != null)
            for (int i : List1)
                if (List2.contains(i))
                    intersection.add(i);

        return intersection;
    }

    /**
     * Returns the intersection of list and a Set passed to it.
     *
     * @param List1 as ArrayList
     * @param List2 as a set
     * @return List
     */
    static ArrayList<Integer> intersection(ArrayList<Integer> List1, Set<Integer> List2) {
        ArrayList<Integer> intersection = new ArrayList<Integer>();
        if (List1 != null && List2 != null)
            if ((!List1.isEmpty()) && (!List2.isEmpty()))
                for (Integer i : List1)
                    if (List2.contains(i))
                        intersection.add(i);

        return intersection;
    }
}

Related

  1. Intersect(ArrayList list1, ArrayList list2)
  2. intersection(ArrayList list1, ArrayList list2)