i got two String type arraylist ..one list containing “book1”, “book2”, “book3” and “book4”. And another arrayList contains “book1”, “book2”, “book3”. So, size of first list
You can transform the lists to sets, and then use Set.retainAll method for intersection between the different sets. Once you intersect all sets, you are left with the common elements, and you can transform the resulting set back to a list.
Only iterate on first arraylist with larger length and check for contains in second arraylist , if found set one else do nothing
for(int counter = 0; counter < firstList.size(); counter++) {
if(secondList.contains(firstList.get(counter))) {
comparingList.set(counter,1);
}
}
Just try to run the below program in http://www.compileonline.com/compile_java_online.php
import java.util.ArrayList;
import java.util.List;
public class CompareArrayListTest{
public static void main(String[] args) {
ArrayList<String> firstList = new ArrayList<String>();
firstList.add("book1");
firstList.add("book2");
firstList.add("book3");
firstList.add("book4");
ArrayList<String> secondList = new ArrayList<String>();
secondList.add("book1");
secondList.add("book2");
secondList.add("book3");
List<Integer> comparingList = new ArrayList<Integer>();
// adding default values as one
for (int a = 0; a < firstList.size(); a++) {
comparingList.add(0);
}
for (int counter = 0; counter < firstList.size(); counter++) {
if (secondList.contains(firstList.get(counter))) {
comparingList.set(counter, 1);
}
}
System.out.println(comparingList);
}
BitSet bitset = new BitSet();
// adding default values as one
for (int a = 0; a < firstList.size(); a++) {
comparingList.add(0);
}
for (int counter = 0; counter < firstList.size(); counter++) {
for (int counter2 = 0; counter < secondList.size(); counter++) {
if (secondList.get(counter2).equals(firstList.get(counter))) {
bitset.set(counter, 1);
}
}
}