카테고리 없음
[JAVA] 두 개의 리스트에서 차집합 구하기
dyana
2025. 1. 3. 09:58
List<Long> A = {1,2,3}
List<Long> B = {2,3,4}
이렇게 두 개의 리스트가 있을 때 내가 구하고 싶은 것은 A의 차집합니다.
// A 리스트의 차집합을 구하는 함수 생성
public static List<Long> findDifference(List<Long> A, List<Long> B) {
Set<Long> setB = new HashSet<>(B);
return A.stream()
.filter(element -> !setB.contains(element))
.collect(Collectors.toList());
}
stream()을 사용한 것은 A의 요소를 stream으로 처리하여 B에 없는 요소만 필터링하기 위해서다.
>>> 추가로
[합집합]에 대하여
List<Long> union = new ArrayList<>(A);
union.addAll(B);
[교집합]에 대하여
List<Long> intersection = A.stream()
.filter(B::contains)
.collect(Collectors.toList());