본문 바로가기

자바(JAVA)
[자바(Java)] Set

//Set : 각 원소가 유일해야 함.

- HashSet : 순서는 상관없을 때 사용. 가장 효율적.

- LinkedHashSet: 삽입 순서대로 저장됨.

- TreeSet: 정렬 기준에 맞춰 저장됨(오름차순)


package collections;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class SetRunner {

    public static void main(String[] args) {

	List<Character> characters = List.of('A', 'Z', 'A', 'B', 'Z', 'F');

	Set<Character> treeSet = new TreeSet<>(characters);
	System.out.println("treeSet: " + treeSet);

	Set<Character> linkedHashSet = new LinkedHashSet<>(characters);
	System.out.println("linkedHashSet: " + linkedHashSet);


	Set<Character> hashSet = new HashSet<>(characters);
	System.out.println("hashSet: " + hashSet);
    } //main

}

// HashSet 

- Set 인터페이스를 구현한 대표적인 컬렉션 클래스

- 순서를 유지하려면 LinkedHashSet 클래스를 사용하면 된다.

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

- 선언 및 생성

Set set명 = new HashSet();


- Hash 구조 + Set 사용법


- 값 추가 : add(o), addAll(c)

- 값 삭제 : remove(o), removeAll(c)

- 값 조건부 삭제 : retainAll(c) //교집합

- 값 전체 삭제 : clear()

- 값 포함 여부 확인 : contains(o), containsAll(c)

- 비어 있는지 확인 : isEmpty()

- 저장된 객체의 개수: size()

- 배열로 반환: Object[] toArray()

- 요소 읽기(향상된 for문)


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

public class Ex12 {
	public static void main(String[] args) {
		Set set = new HashSet();
		set.add(1);
		set.add(1); //중복 추가 x
		set.add(2);
		set.add(3);
		set.add(4);
		set.add(5);
		System.out.println("set = " + set);
		System.out.println("set의 size = " + set.size());
		System.out.println("3을 포함하고 있나요? : " + set.contains(3)+"\n");
		
		set.remove(3);
		System.out.println("3 삭제 후 set = " + set);
		System.out.println("set의 size = " + set.size());
		System.out.println("3을 포함하고 있나요? : " + set.contains(3));
		System.out.println("set이 비어있나요? : " + set.isEmpty() + "\n");
		
		set.clear();
		System.out.println("clear 후 set = " + set);
		System.out.println("set이 비어있나요? : " + set.isEmpty());
	}
}

 


package com.test.collection;

import java.util.HashSet;
import java.util.Iterator;

public class Ex79_HashSet {
	
	public static void main(String[] args) {

		m1();

	} //main

	private static void m1() {
		
		HashSet<String> set = new HashSet<String>();
		
		//1. 요소 추가하기
		set.add("사과");
		set.add("딸기");
		set.add("바나나");
		
		//2. 요소 개수
		System.out.println(set.size());
		System.out.println();
		
		//3. 덤프
		System.out.println(set);
		System.out.println();
		
		//4. 중복된 값 추가하기
		set.add("사과");
		System.out.println(set);
		System.out.println();
	
		//5. 검색
		System.out.println(set.contains("사과"));
		System.out.println();
		
		//6. 삭제
		set.remove("사과");
		System.out.println(set);
		System.out.println();
		
		//7. 요소 읽기 > 향상된 for문 사용
		for (String item : set) {
			System.out.println(item);
		}
		System.out.println();
		
		//이터레이터 > 데이터 집합을 탐색하는 도구 > 탐색기
		Iterator<String> iter = set.iterator();
		
		while(iter.hasNext()) {
			System.out.println(iter.next());
		}
		
	}
	
}

// TreeSet

- 범위 검색과 정렬에 유리한 컬렉션 클래스

- 이진 탐색 트리(bs 트리)로 구현.

- HashSet보다 데이터 추가, 삭제에 시간이 더 걸림.

- import java.util.TreeSet;

- 선언 및 생성

Set set명 = new TreeSet();


- 생성자: TreeSet(), TreeSet(c), TreeSet(comp)

- 가장 작은 값(오름차순) : first()

- 가장 큰 값(오름차순): last()

- 올림1(같거나 큰 값): ceiling(o)

- 버림1(같거나 작은 값): floor(o)

- 올림2(큰 값): higher(o)

- 버림2(작은 값): lower(o)

- 특정 범위 추출: subSet(fromElement, toElement) // fromElement ~ toElement - 1

- 지정 객체보다 작은 값의 객체 반환: headSet(toElement)

- 지정 객체보다 같거나 큰 값의 객체 반환: tailSet(fromElement)

- 값 추가 : add(o), addAll(c)

- 값 삭제 : remove(o), removeAll(c)

- 값 조건부 삭제 : retainAll(c)

- 값 전체 삭제 : clear()

- 값 포함 여부 확인 : contains(o), containsAll(c)

- 비어 있는지 확인 : isEmpty()

- 저장된 객체의 개수: size()

import java.util.TreeSet;

public class Ex13 {
	public static void main(String[] args) {
		TreeSet set = new TreeSet();
		
		set.add(3);
		set.add(4);
		set.add(2);
		set.add(5);
		set.add(1);
		
		System.out.println("set = " + set);
		System.out.println("set의 size = " + set.size());
		System.out.println("3을 포함하고 있나요? : " + set.contains(3));
		
		System.out.println("set의 first() = " + set.first());
		System.out.println("set의 last() = " + set.last());
		
		System.out.println("ceiling(3) = " + set.ceiling(3));
		System.out.println("floor(3) = " + set.floor(3));
		System.out.println("higher(3) = " + set.higher(3));
		System.out.println("lower(3) = " + set.lower(3));
		
		System.out.println("2~3 추출 = " + set.subSet(2, 4));
		System.out.println("headSet(3) = " + set.headSet(3));
		System.out.println("tailSet(2) = " + set.tailSet(2) + "\n");
		
		set.remove(3);
		System.out.println("3 삭제 후 set = " + set);
		System.out.println("set의 size = " + set.size());
		System.out.println("3을 포함하고 있나요? : " + set.contains(3));
		System.out.println("set이 비어있나요? : " + set.isEmpty() + "\n");
		
		System.out.println("ceiling(3) = " + set.ceiling(3));
		System.out.println("floor(3) = " + set.floor(3));
		System.out.println("higher(3) = " + set.higher(3));
		System.out.println("lower(3) = " + set.lower(3) + "\n");		
		
		set.clear();
		System.out.println("clear 후 set = " + set);
		System.out.println("set이 비어있나요? : " + set.isEmpty());
	}
}

package com.test.collection;

import java.util.TreeSet;

public class Ex85_TreeSet {

	public static void main(String[] args) {

		m1();

	} //main

	private static void m1() {
				
		TreeSet<Integer> set = new TreeSet<Integer>();
		
		for(int i = 1; i <= 30; i++) {
			set.add(i);
		}

		System.out.println(set);
		System.out.println(set.first());
		System.out.println(set.last());
		System.out.println(set.headSet(10));
		System.out.println(set.tailSet(20));
		System.out.println(set.subSet(15, 25));
		
	}
	
}

 

'자바(JAVA)' 카테고리의 다른 글

[자바(Java)] 제네릭(Generics)  (1) 2022.12.17
[자바(Java)] Collections  (0) 2022.12.16
[자바(Java)] Comparator와 Comparable  (0) 2022.12.16
[자바(Java)] Arrays  (0) 2022.12.16
[자바(Java)] Iterator  (0) 2022.12.15