본문 바로가기
BackEnd/Java

[Java] 컬렉션 프레임워크(collection framework) 이야기 2부 - Set

by 뽀뽀이v 2020. 9. 18.

Collection Framework

Set Collection

Set의 특징으로는 List와는 다르게 중복 값을 허용하지 않는다.  또한 인덱스로 접근하지 않기 때문에 성능적으로 부족한 면이 있다.

HashSet

Set의 특징답게 중복값을 허용하지 않는다. 같은 요소를 추가하는 경우 false를 반환한다. (이러한 특징을 이용하면 알고리즘에서 중복 제거하기 편할 것이다.) 저장 순서를 유지하지 않으므로 저장 순서를 원한다면 LinkedHashSet을 사용해야 한다. 또한 null값을 저장할 수 있다.

public class Main {
    public static void main(String[] args) {
        // Array
        System.out.println("==== Array ====");
        String[] strings = {"a", "d", "e", "f", "e", "g", "a", "b", "d", "f", "a"};
        // 중복 제거 - 전
        System.out.print("중복 제거 - 전 : ");
        for (String str : strings) {
            System.out.print(str);
        }

        // Set
        System.out.println("==== Set ====");
        Set<String> stringSet = new HashSet<String>();
        stringSet.addAll(Arrays.asList(strings)); // Array to Set
        List<String> list = stringSet.stream().collect(Collectors.toList());
        System.out.println();
        System.out.print("list 변환 : " + list);

        // 중복 제거 - 후
        System.out.println();
        System.out.print("중복 제거 - 후 : ");
        
        // Iterator는 Collection값을 가져오는데 최적화된 클래스이다.
        // hashNext() -> next() -> remove() 3가지 메소드가 있다.
        Iterator it = stringSet.iterator();
        while (it.hasNext()) {
            System.out.print(it.next());
        }

        // Set to Array
        System.out.println();
        stringSet.add(null); // null 값 추가
        Boolean bl = stringSet.add(null); // null 값 추가
        System.out.println(bl);
        strings = new String[stringSet.size()];
        stringSet.toArray(strings);

        System.out.print("null 추가 : ");
        for (String str : strings) {
            System.out.print(str);
        }
    }
}
==== Array ====
중복 제거 - 전 : adefegabdfa
==== Set ====
list 변환 : [a, b, d, e, f, g]
중복 제거 - 후 : abdefg
false
null 추가 : nullabdefg

TreeSet

TreeSet은 이진 탐색 트리(BinarySearchTree) 구조로 이루어져 있다. 일반적인 이진 탐색트리보다 성능을 향상시킨 레드-블랙 트리(Red-Black Tree)로 구현되어 있습니다. 부모노드 보다 작은 값은 왼쪽 자식으로, 큰 값은 오른쪽 자식으로 배치하여 데이터의 추가나 삭제 시 트리의 균형을 유지합니다.

레드-블랙 트리(Red-Black Tree)

public class Main {
    public static void main(String[] args) {
        // Array
        System.out.println("==== Array ====");
        Integer[] integers = {22, 33, 44, 50, 66, 77, 87, 99, 99};

        // Set
        System.out.println("==== Set ====");
        TreeSet<Integer> treeSet = new TreeSet<Integer>(Arrays.asList(integers));
        Iterator it = treeSet.iterator();
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
        System.out.println();
        System.out.println("입력값 보다 작은 수 : " + treeSet.lower(90)); // 없으면 null 리턴
        System.out.println("입력값 보다 큰 수 : " + treeSet.higher(90)); // 없으면 null 리턴
        System.out.println("가장 큰 수 삭제 : " + treeSet.pollLast()); // 가장 큰 수 삭제

        System.out.print("33이상 66미만 내림차순으로 출력 : ");
        NavigableSet<Integer> rangeSet = treeSet.subSet(33, true, 66, false).descendingSet();
        it = rangeSet.iterator();
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
    }
}
==== Array ====
==== Set ====
22 33 44 50 66 77 87 99 
입력값 보다 작은 수 : 87
입력값 보다 큰 수 : 99
가장 큰 수 삭제 : 99
33이상 66미만 역순으로 출력 : 50 44 33 

댓글