[Java] Set 인터페이스란?

1. Set 인터페이스란?

Set 인터페이스는 중복을 허용하지 않고, 순서에 대한 보장이 없는 데이터 집합을 다룰 수 있게 해주는 프레임워크 중 하나다.

  • Setjava.util 패키지에 포함된 인터페이스
  • 중복된 요소를 저장할 수 없고, null도 1개만 허용한다.

Set 인터페이스 주요 구현체

  1. HashSet
    • 가장 일반적인 구현체.
    • 내부적으로 HashMap을 사용.
    • 요소의 순서를 보장하지 않음.
    • 중복 제거 성능이 뛰어남 (hash 기반).
  2. LinkedHashSet
    • HashSet의 확장 버전.
    • 요소가 추가된 순서를 유지.
    • 내부적으로 LinkedList와 HashMap을 함께 사용.
  3. TreeSet
    • 정렬된 순서를 유지.
    • Comparable 또는 Comparator를 통해 정렬 기준 설정 가능.
    • 내부적으로 이진 탐색 트리 (Red-Black Tree) 를 사용.

자주 사용하는 메서드

메서드 설명 반환값
add(값) 요소 추가 boolean
remove(값) (값이 숫자가 아닌경우) 값으로 삭제 boolean
contains(값) 포함 여부 확인 boolean
isEmpty() 비어있는지 확인 boolean
size() 요소 개수 반환 (Set의 크기) int
clear() 모든 요소 제거 void
retainAll(컬렉션) 두 컬렉션에서 같은 것만 남김 boolean

예제 코드

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();

        set.add("apple");
        set.add("banana");
        set.add("apple"); // 중복, 추가 안됨

        System.out.println(set); // [banana, apple] (순서 보장 X)

        System.out.println(set.contains("banana")); // true

        set.remove("apple");
        System.out.println(set); // [banana]
    }
}

2. 주요 구현체의 코드 예시

HashSet

랜덤 저장

import java.util.HashSet;
import java.util.Set;

public class HashSetExample {
    public static void main(String[] args) {
        Set<String> fruits = new HashSet<>();

        fruits.add("apple");
        fruits.add("banana");
        fruits.add("orange");
        fruits.add("banana"); // 중복이므로 추가되지 않음

        System.out.println("HashSet: " + fruits);
    }
}


// 결과: [banana, apple, orange]

LinkedHashSet

순서대로 저장

import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        Set<String> cities = new LinkedHashSet<>();

        cities.add("Seoul");
        cities.add("NewYork");
        cities.add("Paris");
        cities.add("Seoul"); // 중복

        System.out.println("LinkedHashSet: " + cities);
    }
}


// 결과: [Seoul, NewYork, Paris]

TreeSet

기본적으로 오름차순으로 저장 (String 또한 a, b, c… 한글은 가, 나, 다…)

import java.util.Set;
import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        Set<Integer> numbers = new TreeSet<>();

        numbers.add(42);
        numbers.add(7);
        numbers.add(15);
        numbers.add(7); // 중복

        System.out.println("TreeSet: " + numbers);
    }
}


// 결과: [7, 15, 42]

3. 주로 사용하는 메서드

아래 값으로 intersection, union, difference 구하기

import java.util.HashSet;
import java.util.Set;

public class SetOperationsExample {
    public static void main(String[] args) {
        Set<String> setA = new HashSet<>();
        setA.add("apple");
        setA.add("banana");
        setA.add("cherry");

        Set<String> setB = new HashSet<>();
        setB.add("banana");
        setB.add("cherry");
        setB.add("date");
    }
}

교집합 (intersection)

Set<String> intersection = new HashSet<>(setA); // setA 복사
intersection.retainAll(setB); // 교집합 연산
System.out.println("교집합: " + intersection);


// 결과: [banana, cherry]

합집합 (union)

Set<String> union = new HashSet<>(setA); // setA 복사
union.addAll(setB); // 합집합 연산
System.out.println("합집합: " + union);


// 결과: [banana, cherry, apple, date]

차집합 (difference)

Set<String> difference = new HashSet<>(setA); // setA 복사
difference.removeAll(setB); // 차집합 연산
System.out.println("차집합 (A - B): " + difference);


// 결과: [apple]

4. 주로 어디에 사용될까?

SNS

Set<String> userAFollowings = ...; // A가 팔로우한 사람
Set<String> userBFollowings = ...;  // B가 팔로우한 사람
Set<String> mutualFollows = new HashSet<>(userAFollowings);
mutualFollows.retainAll(userBFollowers);
  1. 함께 팔로우하는 사람
    • userAFollowingsuserBFollowers 두 Set의 교집합
  2. 사용자 A와 B가 좋아하는 태그의 교집합을 통해 취향이 비슷한 친구 추천

쇼핑몰

Set<String> cartItems = new HashSet<>();
cartItems.add("item1");
cartItems.add("item1"); // 중복 안 됨
  1. 중복 없는 장바구니: 같은 상품을 여러 번 담아도 1개로 처리해야 할 때
  2. 이전에 본 상품 vs 신규 추천 상품 비교: Set을 이용해서 사용자가 이미 본 상품을 추천 목록에서 제거 (차집합)
  3. 검색 및 추천 시스템: 사용자 A가 본 영화 목록과 사용자 B가 본 영화 목록의 교집합이 많으면? B를 A의 유사 사용자로 판단

Set은 자바에서 교집합, 합집합, 차집합 같은 집합 연산을 할 때 가장 많이 사용되는 인터페이스다.

Categories:

Updated:

Leave a comment