Risk
Risk

Reputation: 111

Compare two array-list element and get un-common element

-- But my output is like this :

[C, E, B, D, F]
[C, B, D, F]
[C, D, F]
[C, F]
[C]

-- i am having same elements in arraylist 2, then also i am getting 'C', it should be null .i.e zero un-common value.

Upvotes: 2

Views: 5509

Answers (4)

Parsania Hardik
Parsania Hardik

Reputation: 4623

Just replace break; with this:

j = -1;

code:

 for (int i = 0; i < al.size(); i++) {
        for (int j = 0; j < a2.size(); j++) {

            if (al.get(i).equals(a2.get(j))) {
                a2.remove(j);
                Log.e("array 2 ", a2.toString());
                j = -1;

            }

        }
    }

Upvotes: 0

juliocb92
juliocb92

Reputation: 96

I recommend you to use Set's instead of ArrayList. You can find some info here.

Also, here you can read some examples of using java Set in set operations in this stackoverflow answer.

Upvotes: 0

Abhishek Patel
Abhishek Patel

Reputation: 4328

Try This it will help you

     ArrayList<String> al = new ArrayList<String>();
     ArrayList<String> a2 = new ArrayList<String>();

    al.add("C");
    al.add("A");
    al.add("E");
    al.add("B");
    al.add("D");
    al.add("F");

    a2.add("C");
    a2.add("C");
    a2.add("E");
    a2.add("B");
    a2.add("D");
    a2.add("F");

   Integer a = null;
 for (int i=0; i<a1.size(); i++)
  {
    a = a1.get(i);

    if (a2.contains(a)
{
    a2.remove(a);
    a1.remove(a);
    i--;
 }
 }

ArrayList<String> finaldata = new ArrayList<String>();
finaldata.addAll(a1);
finaldata.addAll(a2);
// finaldata = { A}

Upvotes: 1

HendraWD
HendraWD

Reputation: 3043

You are messing with the index when you remove the a2 items directly inside for loop. Refer to my solution below

        ArrayList<String> al = new ArrayList<>();
        ArrayList<String> a2 = new ArrayList<>();
        al.add("C");
        al.add("A");
        al.add("E");
        al.add("B");
        al.add("D");
        al.add("F");

        a2.add("C");
        a2.add("C");
        a2.add("E");
        a2.add("B");
        a2.add("D");
        a2.add("F");

        ArrayList<String> tempToDelete = new ArrayList<>();

        for (int i = 0; i < al.size(); i++) {
            for (int j = 0; j < a2.size(); j++) {
                if (al.get(i).equals(a2.get(j))) {
                    tempToDelete.add(a2.get(j));
                    break;
                }

            }
        }

        a2.removeAll(tempToDelete);

for shorter method, you can just do this:

a2.removeAll(al);

Upvotes: 3

Related Questions