Write a method numInCommon that takes 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).
I'd like feedback on how to make this code better. Are there better ways to do it? If I wasn't following the prompt (e.g. no set required), how could I find the common elements in the laziest, most efficient, best optimized, etc. way? Last but not least, does my code have any major bugs?
public static int numInCommon(List<Integer> list1, List<Integer> list2) {
if (list1.isEmpty() || list2.isEmpty()) {
return 0;
} else {
Set<Integer> setCommon = new HashSet<Integer>();
for (Integer val : list1) {
// add the values of list1 to the set
setCommon.add(val);
}
int common = 0;
for (Integer val : list2) {
if (setCommon.contains(val)) {
// if a value in list2 exists in the set, increase common
common++;
setCommon.remove(val);
}
}
return common;
}
}