my title is bad but I don’t have an idea what it should be. My question is simple, I have four arraylist and I want to get similar words from two of them and put another arraylists. Anyway my array lists like;
arrList1 = {car, apple, many, car, tyty, man, superman}; arrList2 = {stack, vs, etc, vs, car, tyty, stack, tyty, many, car, apple};
I tried this;
for (int i = 0; i < arrList1.size(); i++) { for (int j = 0; j < arrList2.size(); j++) { if (arrList1.get(i).equals(arrList2.get(j))) { arrList3.add(arrList1.get(i); arrList4.add(arrList2.get(j); } }
But as you see arrList1 and arrList2 have duplicates so arrList4 will have same element more than normal. Also I have to count elements which are in arrList1 and arrList2 so I shouldn’t use Set Collections. What should I do?
Advertisement
Answer
Try
ArrayList<String> temp = new ArrayList<String>(); boolean found = false; for (int i = 0; i < arrList1.size(); i++) { found = false; for (int j = 0; j < arrList2.size(); j++) { if (arrList1.get(i).equals(arrList2.get(j))) { found = true; if (!temp.contains(arrList2.get(j)) { arrList4.add(arrList2.get(j)); } } } if (found) { arrList3.add(arrList1.get(i)); temp.add(arrList1.get(i)); } }
This will check if the new ArrayList
does not already contain the item.