Common elements in two lists

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

    Use Collection#retainAll().

    listA.retainAll(listB);
    // listA now contains only the elements which are also contained in listB.
    

    If you want to avoid that changes are being affected in listA, then you need to create a new one.

    List common = new ArrayList(listA);
    common.retainAll(listB);
    // common now contains only the elements which are contained in listA and listB.
    

提交回复
热议问题