The question is how to add common arraylist elements to the third arraylist using for loop

I am trying to compare two arrays of ArrayLists, and after comparing I should get common elements between these two arraylists and show them in the third arraylist.

This is my code, here newList is an arraylist in which I want to add common elements, but every time I add elements in this arraylist, it only displays the last element.

            ArrayList<String> list2 = new ArrayList<String>();
    list2.add("1");
    list2.add("abc");
    list2.add("3");
    list2.add("4");
    ArrayList<String> list1 = new ArrayList<String>();
    list1.add("3");
    list1.add("4"); list1.add("7");
    list1.add("8");

    list1.add("12");
    list1.add("4");
    list1.add("53");
    list1.add("2");
    list1.add("62");
    list1.add("abc");

    System.out.println("btn click r_answer "+list1+" "+list2);

     for (int i=0;i<list1.size();i++) {
            for (int j=0;j<list2.size(); j++) {
                if(list1.get(i).equals(list2.get(j)))
                    System.out.println("equals..:"+list2.get(j));
                         newList.add(list2.get(j));
                }
            }
+4
source share
3 answers

save curly braces after condition for loop ...

for (int i=0;i<list1.size();i++) {
        for (int j=0;j<list2.size(); j++) {
            if(list1.get(i).equals(list2.get(j))){
                System.out.println("equals..:"+list2.get(j));
                newList.add(list2.get(j));
            }
        }
    }
+5
source

try this ... An easy way to get common elements in two ArrayLists

    ArrayList<String> list2 = new ArrayList<String>();
    // add the elements into list2
    ArrayList<String> list1 = new ArrayList<String>();
    // add the elements into list1

    ArrayList<String> newList = new ArrayList<String>(list1);
    newList.retainAll(list2);

    // Now newList will contain common elements
+2
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);
0

Source: https://habr.com/ru/post/1528044/


All Articles