Common elements in two lists

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

    You can get the common elements between two lists using the method "retainAll". This method will remove all unmatched elements from the list to which it applies.

    Ex.: list.retainAll(list1);
    

    In this case from the list, all the elements which are not in list1 will be removed and only those will be remaining which are common between list and list1.

    List list = new ArrayList<>();
    list.add(10);
    list.add(13);
    list.add(12);
    list.add(11);
    
    List list1 = new ArrayList<>();
    list1.add(10);
    list1.add(113);
    list1.add(112);
    list1.add(111);
    //before retainAll
    System.out.println(list);
    System.out.println(list1);
    //applying retainAll on list
    list.retainAll(list1);
    //After retainAll
    System.out.println("list::"+list);
    System.out.println("list1::"+list1);
    

    Output:

    [10, 13, 12, 11]
    [10, 113, 112, 111]
    list::[10]
    list1::[10, 113, 112, 111]
    

    NOTE: After retainAll applied on the list, the list contains common element between list and list1.

提交回复
热议问题