Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the differences from 2 ArrayLists of Strings?

I have 2 Strings:

A1=[Rettangolo, Quadrilatero, Rombo, Quadrato]
A2=[Rettangolo, Rettangolo, Rombo, Quadrato]

I want to obtain this: "I have found "Quadrilatero", instead of "Rettangolo" ". If I use removeAll() or retainAll() it doesn't work because I have 2 instances of "Rettangolo". In fact, if I use a1.containsAll(a2), I get true and I want false.

Thanks all for considering my request.

like image 911
Lorenzo Calosci Avatar asked Feb 16 '23 08:02

Lorenzo Calosci


1 Answers

Use the remove method from ArrayList. It only removes the first occurance.

public static void main(String []args){
        //Create ArrayLists
        String[] A1 = {"Rettangolo", "Quadrilatero", "Rombo", "Quadrato"};
        ArrayList<String> a1=new ArrayList(Arrays.asList(A1));
        String[] A2 ={"Rettangolo", "Rettangolo", "Rombo", "Quadrato"};
        ArrayList<String> a2=new ArrayList(Arrays.asList(A2));
        // Check ArrayLists
        System.out.println("a1 = " + a1);
        System.out.println("a2 = " + a2);
        // Find difference
        for( String s : a1)
            a2.remove(s);
        // Check difference
        System.out.println("a1 = " + a1);
        System.out.println("a2 = " + a2);
}

Result

a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo, Rettangolo, Rombo, Quadrato]
a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo]
like image 52
AnthonyW Avatar answered Feb 23 '23 05:02

AnthonyW