day 19
package api.util.collection2;
import java.util.ArrayList;
import java.util.List;
public class Test05 {
public static void main(String[] args) {
//집합 연산
List<Integer> a = new ArrayList<>();
a.add(1);
a.add(2);
a.add(3);
List<Integer> b = new ArrayList<>();
b.add(3);
b.add(4);
b.add(5);
List<Integer> c = new ArrayList<>();
c.addAll(b);
c.addAll(a);
System.out.println(c);
}
}
List를 사용해서 합집합을 구한다면
사용된 명령 : .addAll
c : [3 4 5 1 2 3]
= 중복이 생긴다 ..!
그러나 Set을 사용한다면?
package api.util.collection2;
import java.util.Set;
import java.util.TreeSet;
public class Test06 {
public static void main(String[] args) {
//집합 연산
Set<Integer> a = new TreeSet<>();
a.add(1);
a.add(2);
a.add(3);
Set<Integer> b = new TreeSet<>();
b.add(3);
b.add(4);
b.add(5);
//합집합(a∪b)
Set<Integer> c = new TreeSet<>();
c.addAll(b);
c.addAll(a);
System.out.println(c);
//교집합(a∩b)
Set<Integer> d = new TreeSet<>();
d.addAll(a);
d.retainAll(b);
System.out.println(d);
//차집합(a-b, b-a)
Set<Integer> e = new TreeSet<>();
e.addAll(a);
e.removeAll(b);
System.out.println(e);
}
}
Set을 사용해서
- 합집합
.addAll
c : [1 2 3 4 5]
심지어 정렬까지 됨 !
- 교집합
.addAll
.retainAll : 겹치는 데이터만 나옴
- 차집합
.addAll
.removeAll
집합연산 예제
# 집합연산
## Test07
다음 요구사항에 따른 계산을 수행하여 결과를 출력하시오.
- 철수와 영희는 각자 국내에서 상영하는 영화를 다음과 같이 봤습니다.
- 철수 : `이상한 나라의 수학자`, `더 배트맨`, `인민을 위해 복무하라`, `블랙라이트`
- 영희 : `더 배트맨`, `스파이더맨 : 노웨이 홈`, `블랙라이트`, `우리가 사랑이라고 믿는 것`
- (Q) 철수와 영희가 둘 다 본 영화 목록을 출력하세요
- (Q) 철수와 영희 중 한 명만 본 영화 목록을 출력하세요
풀이
'Hardcode > java' 카테고리의 다른 글
LIST, MAP, SET의 차이 (0) | 2023.01.15 |
---|---|
Map - HashMap (0) | 2022.08.21 |
Collection - ArrayList, LinkedList, TreeSet, HashSet (0) | 2022.08.21 |
Collection - Set, List와의 차이 (0) | 2022.08.20 |
Collection - List (3) | 2022.08.20 |