Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issue in adding common elements of arraylist in third arraylist using for loop [duplicate]

I am trying to compare two ArrayLists, and after comparision i have to get common elements between those two arraylists and show them in a third arraylist.

This is my code, here newList is the arraylist in which i want to add the common elements but each time i am adding elements in this arraylist it is showing only 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));
                }
            }
like image 652
Vaishali Sharma Avatar asked Mar 21 '23 12:03

Vaishali Sharma


1 Answers

keep braces after if condition in 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));
            }
        }
    }
like image 95
Anil kumar Avatar answered Apr 06 '23 11:04

Anil kumar