Java/Spring
[JAVA] 두 개의 리스트에서 중복 값 제거 HashSet 사용하기
dyana
2025. 1. 3. 09:39
List<Long> A = {3}
List<Long> B = {3,5,6}
A와 B의 리스트에서 중복된 값을 제거하고 싶을 때
// 중복 값을 찾기 위해 HashSet 사용
HashSet<Long> setA = new HashSet<>(A);
HashSet<Long> setB = new HashSet<>(B);
// 교집합을 구해 중복된 값 확인
HashSet<Long> intersection = new HashSet<>(setA)
intersection.retainAll(setB);
// 결과 리스트
List<Long> result = new ArrayList<>();
//A의 중복되지 않은 값 추가
for (Long num : A) {
if (!intersection.contains(num)) {
result.add(num);
}
}
// B의 중복되지 않은 값 추가
for (Long num : B) {
if (!intersection.contains(num)) {
result.add(num);
}
}