티스토리 뷰

728x90
반응형

목차

     

    지난 한 주간은 백준에서 집합과 관련된 문제를 주로 풀었다.

     

    그러면서 해시 셋과 트리 셋의 특성에 대해 전보다 익숙해진 느낌이 들어 든든한 느낌도 든다.

     

    어쨌거나 집합과 맵에 대한 문제를 풀어본 김에, 자바 컬렉션 프레임워크에서 제공하는

     

    집합과 관련된 메서드를 정리하고 가면 좋겠다는 생각이 들었다.

     

    대단히 어려운 내용은 없지만, 그림과 함께 하나씩 정리하자.

     

    먼저, 아래와 같은 셋 두 개를 준비한다.

    public class example {
    
        public static void main(String[] args) {
    
            Set<Integer> treeSet = new TreeSet<>(List.of(1, 2, 3, 4, 5));
            Set<Integer> hashSet = new HashSet<>(List.of(4, 5, 6, 7, 8));
        }
    }

     

    Union, addAll()

     

    합집합은 말 그대로 두 개의 집합을 빠짐없이 결합해 만들어진 집합이다.

     

    SQL에 익숙한 사람은 Full Outer Join과 같다고 생각해도 틀리지 않을 것 같다.

     

    자바는 합집합을 만드는 addAll() 메서드를 제공한다.

    public class example {
    
        public static void main(String[] args) {
    
            Set<Integer> treeSet = new TreeSet<>(List.of(1, 2, 3, 4, 5));
            Set<Integer> hashSet = new HashSet<>(List.of(4, 5, 6, 7, 8));
    
            treeSet.addAll(hashSet);
    
            treeSet.forEach(element -> System.out.print(element + " "));
        }
    }
    1 2 3 4 5 6 7 8

     

    Intersection, retainAll

     

    교집합은 두 집합에 모두 속하는, 그러니까 공통 원소를 모은 집합이다.

     

    역시 SQL에 빗대자면 Inner Join과 같을 것이다.

     

    자바에서 교집합을 만드는 메서드는 retainAll()이며, 그 사용법은 아래와 같다.

    public class example {
    
        public static void main(String[] args) {
    
            Set<Integer> treeSet = new TreeSet<>(List.of(1, 2, 3, 4, 5));
            Set<Integer> hashSet = new HashSet<>(List.of(4, 5, 6, 7, 8));
    
            treeSet.retainAll(hashSet);
    
            treeSet.forEach(element -> System.out.print(element + " "));
        }
    }
    4 5

     

    Difference of sets, removeAll()

     

    차집합은 A집합에서 B집합에 속하는 원소를 모두 제거한, 순수하게 A에만 속한 원소의 집합이다.

     

    SQL에선 Left Outer Join을 할 때 B의 Id가 null인 경우를 선택하는 경우와 같다.

     

    자바에선 메서드 removeAll()이 제공된다.

    public class example {
    
        public static void main(String[] args) {
    
            Set<Integer> treeSet = new TreeSet<>(List.of(1, 2, 3, 4, 5));
            Set<Integer> hashSet = new HashSet<>(List.of(4, 5, 6, 7, 8));
    
            treeSet.removeAll(hashSet);
    
            treeSet.forEach(element -> System.out.print(element + " "));
        }
    }
    1 2 3

     

    Subset, containsAll

     

    부분집합은 B집합이 A집합에 완전히 속해있는 경우를 말한다.

     

    containsAll() 메서드를 이용해 부분집합 관계를 boolean으로 리턴 받을 수 있다.

    public class example {
    
        public static void main(String[] args) {
    
            Set<Integer> treeSet = new TreeSet<>(List.of(1, 2, 3, 4, 5));
            Set<Integer> hashSet = new HashSet<>(List.of(4, 5, 6, 7, 8));
    
            System.out.println(treeSet.containsAll(hashSet));
        }
    }
    false

     

    public class example {
    
        public static void main(String[] args) {
    
            Set<Integer> treeSet = new TreeSet<>(List.of(1, 2, 3, 4, 5));
            Set<Integer> hashSet = new HashSet<>(List.of(4, 5));
    
            System.out.println(treeSet.containsAll(hashSet));
        }
    }
    true

    알고리즘에서 등장하는 대부분의 집합 연산은 위의 네 가지를 적당히 조절하면 풀 수 있는 것 같다.

     

    실제 프로젝트에서 Set<T>의 활용도는 아직 체감하지 못할 수준이기는 하지만..

     

    컴퓨터는 기본적으로 계산기니까 이런 기능도 파악하고 있는 게 좋은 길이라 생각이 든다.

    반응형
    댓글
    공지사항
    최근에 올라온 글
    최근에 달린 댓글
    Total
    Today
    Yesterday
    링크
    «   2024/06   »
    1
    2 3 4 5 6 7 8
    9 10 11 12 13 14 15
    16 17 18 19 20 21 22
    23 24 25 26 27 28 29
    30
    글 보관함