Java에서 리스트의 요소가 다른 리스트에 포함되지 않는지 확인할 때 Collections.disjoint() 메서드를 사용하면 간단하게 처리할 수 있습니다.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> targetList = Arrays.asList("A", "B", "C");
List<String> statusList = Arrays.asList("X", "Y", "Z");
boolean isDisjoint = Collections.disjoint(targetList, statusList);
System.out.println(isDisjoint); // true (겹치는 요소 없음)
}
}
Collections.disjoint(targetList, statusList)는 두 리스트에 공통 요소가 없으면 true를 반환하고, 하나라도 공통 요소가 있으면 false를 반환합니다.
또한, 스트림을 이용해서 동일한 기능을 구현할 수도 있습니다.
boolean allNotExist = targetList.stream().noneMatch(statusList::contains);
이 방법 역시 targetList의 모든 요소가 statusList에 없는 경우 true를 반환합니다. noneMatch() 메서드는 statusList에 포함된 요소가 하나라도 있으면 false를 반환하기 때문에 Collections.disjoint()와 동일한 기능을 수행합니다.
위 방법을 활용하면 리스트 간의 겹치는 요소 여부를 효과적으로 확인할 수 있습니다.
반응형
'개발 (Development) > Java' 카테고리의 다른 글
| [Java/SpringBoot] Kubernetes 환경에서 Spring Boot 로그를 Pod별로 Rolling 하도록 설정 (0) | 2025.04.19 |
|---|---|
| [Java/MyBatis] MyBatis <foreach>에서 #{}와 ${} 차이, 그리고 item 두 번 쓰기 (0) | 2025.04.05 |
| [Java] API 요청 및 응답 시 비동기 처리 (0) | 2024.12.30 |
| [Java/JPA] JPQL 파라미터 바인딩 (위치 기반) (0) | 2024.04.11 |
| [Java] String to Date (0) | 2024.04.11 |