Java
집합자료형
sm_hope
2022. 6. 21. 10:43
집합에 다음과 같은 값이 있다고 해보자
HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
HashSet<Integer> s2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));
차집합
HashSet<Integer> substract = new HashSet<>(s1); // s1으로 substract 생성
substract.removeAll(s2); // 차집합 수행
substract를 새로 생성해 주는 이유는 집합자료형을 사용하면 원래 값을 변화하기 때문에 원본에대해 알 수 없어 저장용 집합을 하나 만들어 준것이다.
교집합
HashSet<Integer> intersection = new HashSet<>(s1); // s1으로 intersection 생성
intersection.retainAll(s2); // 교집합 수행
합집합
HashSet<Integer> union = new HashSet<>(s1); // s1으로 union 생성
union.addAll(s2); // 합집합 수행