Write a method countCommon that accepts two lists of integers as parameters and returns the number of unique integers that occur in both lists. Use one or more sets as storage to help you solve this problem. For example, if one list contains the values (3, 7, 3, –1, 2, 3, 7, 2, 15, 15) and the other list contains the values (–5, 15, 2, –1, 7,15, 36), your method should return 4 because the elements –1, 2, 7, and 15 occur in both lists.
package collections;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CountCommon {
public static int countCommon(List<Integer> list1, List<Integer> list2) {
int offset = 0;
Set<Integer> set1 = new HashSet<Integer>(list1);
Set<Integer> set2 = new HashSet<Integer>(list2);
// this for each loop each element in set2 if it contains elemnet which alredy
// in set1 it will offset by one.
for (int common : set2) {
if (set1.contains(common))
offset++;
}
// returns the offset count
return offset;
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, 10, 2, 12, 6, 14, 5, 16);
List<Integer> list1 = new ArrayList<Integer>();
Collections.addAll(list1, 2, 7, 2, 0, 12, 14, 16);
System.out.println("Total common elements in the both lists is: " +countCommon(list,list1));
}
}
Output:
Total common elements in the both lists is: 4