I have two ArrayList objects with three integers each. I want to find a way to return the common elements of the two lists. Has anybody an idea how I can achiev
public static List getCommonElements(
java.util.Collection a,
java.util.Collection b
) {
if(a==null && b==null) return new ArrayList<>();
if(a!=null && a.size()==0) return new ArrayList<>(b);
if(b!=null && b.size()==0) return new ArrayList<>(a);
Set set= a instanceof HashSet?(HashSet)a:new HashSet<>(a);
return b.stream().filter(set::contains).collect(Collectors.toList());
}
For better time performance, please use HashSet (O(1) look up) instead of List(O(n) look ups)
Time complexity- O(b) Space Complexity- O(a)