Common elements in two lists

后端 未结 14 1156
无人共我
无人共我 2020-11-22 12:22

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

14条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 12:42

    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)

提交回复
热议问题