[자료구조] Set : 집합

김피자·2023년 2월 20일
0

자료구조

목록 보기
3/4

합집합/ 차집합/ 교집합

합집합은 addAll, 차집합은 removeAll, 교집합은 retainAll을 사용해 집합을 구하는데 이 과정에서 contains를 사용해 중복되는 요소를 찾게된다.

List 중복요소 제거

addAll

List<String> list = Arrays.asList("A", "B", "C", "A", "B", "C");
Set<String> set = new HashSet<>(list);
System.out.println(set);

//[A, B, C]

단순히 Set에 리스트 그대로 넣어서 중복을 제거

List<String> list = Arrays.asList("A", "B", "C", "A", "B", "C");
Set<String> set = new HashSet<>(list);
List<String> list2 = new LinkedList<>(set);
System.out.println(list2);

//[A, B, C]

Set을 다시 List로 만들기

stream

List<String> list = Arrays.asList("A", "B", "C", "A", "B", "C");
List<String> list2 = list.stream().distinct().collect(Collectors.toList());
System.out.println(list2);

//[A, B, C]

stream의 distinct를 사용해 중복을 제거
stream을 다시 List로 만들기위해서는 collect를 사용하면 된다.

List로 Set 효과 내기

합집합

<T> List<T> union(List<T> list1, List<T> list2){
	List<T> union = new LinkedList<>();
    union.addAll(list1);
    for(T t : list2) if(!union.contains(t) union.add(t);
    return union;
}

차집합

<T> List<T> difference(List<T> list1, List<T> list2){
	List<T> difference = new LinkedList<>();
    difference.addAll(list1);
    for(T t : list2) difference.remove(t);
    return difference;
}

교집합

<T> List<T> intersection(List<T> list1, List<T> list2){
	List<T> intersection = new LinkedList<>();
    union.addAll(list1);
    for(T t : list2) if(list2.contains(t)) intersection.add(t);
    return intersection;
}
profile
제로부터시작하는코딩생활

0개의 댓글