-2

I have six values that I have stored store in ArrayList.. How to get common values from that array list?

****What I have tried:****

    aList1 = new ArrayList<String>();    
        aList1.add(value1);
        aList1.add(value2);
        aList1.add(value3);
        aList1.add(value4);
        aList1.add(value5);
        aList1.add(value6);      

     aList2 = new ArrayList<String>();    
            aList2.add(value1);
            aList2.add(value2);
            aList2.add(value3);
            aList2.add(value4);
            aList2.add(value5);
            aList2.add(value6);

String []sCommon = alist1.compare(alist2)    

Toast.makeText(getApplicationContext(), "" + sCommon, Toast.LENGTH_LONG).show();

2 Answers2

1

Use Collection#retainAll().

listA.retainAll(listB);

listA now contains only the elements which are also contained in listB. If you want to avoid that changes are being affected in listA, then you need to create a new one.

List<Integer> common = new ArrayList<Integer>(listA);
common.retainAll(listB);

common now contains only the elements which are contained in listA and listB.

0

check this you can get duplicate value from ArrayList.

Finding duplicate values in arraylist

other way you can remove duplicate element like this

List<String> al = new ArrayList<>();
// add elements to al, including duplicates
Set<String> hs = new HashSet<>();
hs.addAll(al);
al.clear();
al.addAll(hs);

Hop it help you

Community
  • 1
  • 1
RushDroid
  • 1,570
  • 3
  • 21
  • 46