Program to find out the number of matching elements in 2 lists

Posted: October 14, 2011 in Collection Framework, Java

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CompareLists {

private static int compareUnsortedLists(List<String> list1, List<String> list2) {

int counter = 0;

Iterator<String> iter = list2.iterator();
while (iter.hasNext()) {
String element = iter.next();
if (list1.contains(element) && element != null) {
counter++;
}
}
return counter;

}

public static void main(String[] args) {

// declare and populate list lst1
List<String> lst1 = new ArrayList<String>();
lst1.add(“alpha”);
lst1.add(“tau”);
lst1.add(“beta”);
lst1.add(“kappa”);
lst1.add(“gamma”);
lst1.add(“delta”);

// declare and populate list lst2
List<String> lst2 = new ArrayList<String>();
lst2.add(“tim”);
lst2.add(“gamma”);
lst2.add(“beta”);
lst2.add(“peter”);
lst2.add(“kappa”);

System.out.println(“Program to find out the number of matching elements in 2 lists”);
// Call compareUnsortedLists
System.out.println(“The number of common elements is: ” + compareUnsortedLists(lst1, lst2));

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s