retainAll

메서드 시그니처

boolean retainAll(Collection<?>c)

예제 1

List<Integer>list1=newArrayList<>(List.of(1,2,3,4,5));
List<Integer>list2=List.of(2,4,6);

list1.retainAll(list2);

System.out.println(list1); // [2, 4]

list2에 있는 값만 남았습니다.


예제 2

Set<String>set1=newHashSet<>(Set.of("A","B","C"));
Set<String>set2=Set.of("B","C","D");

set1.retainAll(set2);

System.out.println(set1); // [B, C]

removeAll()과 비교

list.retainAll(other);

↓

교집합

현재: [1,2,3,4]
상대: [3,4,5]

결과: [3,4]