Common elements in two lists

后端 未结 14 803
无人共我
无人共我 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<Integer> common = new ArrayList<Integer>(listA);
    common.retainAll(listB);
    // common now contains only the elements which are contained in listA and listB.
    
    0 讨论(0)
  • 2020-11-22 13:00
    List<Integer> listA = new ArrayList<>();
        listA.add(1);
        listA.add(5);
        listA.add(3);
        listA.add(4);   
    
    List<Integer> listB = new ArrayList<>();
        listB.add(1);
        listB.add(5);
        listB.add(6);
        listB.add(7);
    System.out.println(listA.stream().filter(listB::contains).collect(Collectors.toList()));
    
    
    Java 1.8 Stream API Solutions
    

    Output [1, 5]

    0 讨论(0)
提交回复
热议问题