Common elements in two lists

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

    You can use set intersection operations with your ArrayList objects.

    Something like this:

    List l1 = new ArrayList();
    
    l1.add(1);
    l1.add(2);
    l1.add(3);
    
    List l2= new ArrayList();
    l2.add(4);
    l2.add(2);
    l2.add(3);
    
    System.out.println("l1 == "+l1);
    System.out.println("l2 == "+l2);
    
    List l3 = new ArrayList(l2);
    l3.retainAll(l1);
    
        System.out.println("l3 == "+l3);
    

    Now, l3 should have only common elements between l1 and l2.

    CONSOLE OUTPUT
    l1 == [1, 2, 3]
    l2 == [4, 2, 3]
    l3 == [2, 3]
    

提交回复
热议问题