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));
}
}
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));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With