Taha Körkem Taha Körkem - 3 months ago 24
Java Question

Intersection of Two Dimensional ArrayList in Java

I want to intersection list1, list2 and list3 in a ArrayList.
So, I want to intersection ArrayLists of arrayList2D. arrayList2D can contain (max) six ArrayList. How I can do?

That's intersection of two Lists.

public <T> List<T> intersection(List<T> list1, List<T> list2) {
List<T> list = new ArrayList<T>();

for (T t : list1) {
if(list2.contains(t)) {
list.add(t);
}
}

return list;
}


That's my codes

ArrayList<ArrayList<Integer>> arrayList2D=new ArrayList<ArrayList<Integer>>();

ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(0);
list1.add(8);
list1.add(15);
list1.add(26);
list1.add(124);
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(0);
list2.add(7);
list2.add(17);
list2.add(26);
list2.add(178);
ArrayList<Integer> list3 = new ArrayList<Integer>();
list3.add(4);
list3.add(8);
list3.add(12);
list3.add(26);
list3.add(128);

arrayList2D.add(list1);
arrayList2D.add(list2);
arrayList2D.add(list3);

Answer

Ok so as per my understanding you need to intersect all arraylists contain under arrayList2D.

public <T> List<T> intersection(List<T> list1, List<T> list2) {
        List<T> list = new ArrayList<T>();

        for (T t : list1) {
            if(list2.contains(t)) {
                list.add(t);
            }
        }

        return list;
    }

make other method which you need to call

public static List<Integer> getAllIntersection(ArrayList<ArrayList<Integer>> arrayList2D){
        List<Integer> finalList =arrayList2D.get(0);
        for(int i=1;i<arrayList2D.size();i++){

            finalList=intersection(finalList,arrayList2D.get(i));
        }
        System.out.println("firstList"+finalList);
        return finalList;
    }

then finaly call getAllIntersection(arrayList2D) to get desire result