본문 바로가기
Programming/Java

[Java] 자바 HashSet 정렬법

by 서현 SEOHYEON 2023. 7. 7.

💚 HashSet 정렬법

- HashSet 클래스는 원소들을 정렬된 순서로 저장하지 않는다.

- HashSet 자체로는 정렬을 할 수 없다.

- 그러나 List로 변환하여 정렬을 하면 가능하다.

 

💚 예시

import java.util.HashSet;
import java.util.ArrayList;
import java.util.Collections;

public class HashSetSortingExample {
    public static void main(String[] args) {
        // HashSet 생성
        HashSet<String> hashSet = new HashSet<>();
        
        // HashSet에 원소 추가
        hashSet.add("Apple");
        hashSet.add("Banana");
        hashSet.add("Orange");
        
        // HashSet을 ArrayList로 변환
        ArrayList<String> arrayList = new ArrayList<>(hashSet);
        
        // ArrayList 정렬
        Collections.sort(arrayList);
        
        // 정렬된 ArrayList 출력
        for (String element : arrayList) {
            System.out.println(element);
        }
    }
}

- 출력 결과

Apple
Banana
Orange

댓글