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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…