Common elements in two lists

后端 未结 14 825
无人共我
无人共我 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:53

    Some of the answers above are similar but not the same so posting it as a new answer.

    Solution:
    1. Use HashSet to hold elements which need to be removed
    2. Add all elements of list1 to HashSet
    3. iterate list2 and remove elements from a HashSet which are present in list2 ==> which are present in both list1 and list2
    4. Now iterate over HashSet and remove elements from list1(since we have added all elements of list1 to set), finally, list1 has all common elements
    Note: We can add all elements of list2 and in a 3rd iteration, we should remove elements from list2.

    Time complexity: O(n)
    Space Complexity: O(n)

    Code:

    import com.sun.tools.javac.util.Assert;
    import org.apache.commons.collections4.CollectionUtils;
    
        List list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
        list1.add(5);
    
        List list2 = new ArrayList<>();
        list2.add(1);
        list2.add(3);
        list2.add(5);
        list2.add(7);
        Set toBeRemoveFromList1 = new HashSet<>(list1);
        System.out.println("list1:" + list1);
        System.out.println("list2:" + list2);
        for (Integer n : list2) {
            if (toBeRemoveFromList1.contains(n)) {
                toBeRemoveFromList1.remove(n);
            }
        }
        System.out.println("toBeRemoveFromList1:" + toBeRemoveFromList1);
        for (Integer n : toBeRemoveFromList1) {
            list1.remove(n);
        }
        System.out.println("list1:" + list1);
        System.out.println("collectionUtils:" + CollectionUtils.intersection(list1, list2));
        Assert.check(CollectionUtils.intersection(list1, list2).containsAll(list1));
    

    output:

    list1:[1, 2, 3, 4, 5]
    list2:[1, 3, 5, 7]
    toBeRemoveFromList1:[2, 4]
    list1:[1, 3, 5]
    collectionUtils:[1, 3, 5]
    

提交回复
热议问题