intersection two array - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

intersection two array

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] argv) {
        Object[] array1 = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        Object[] array2 = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(intersection(array1, array2));
    }/*w  w w  . jav  a2s. c  om*/

    static public List intersection(Object[] array1, Object[] array2) {
        ArrayList result = new ArrayList();
        if (array1 != null && array2 != null) {
            for (int i = 0; i < array1.length; i++) {
                Object o1 = array1[i];
                for (int j = 0; j < array2.length; j++) {
                    Object o2 = array2[j];
                    if (o2.equals(o1)) {
                        result.add(o1);
                    }
                }
            }
        }
        return result;
    }
}

Related Tutorials