Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- javascript
- 인출수수료
- 급성심근경색증
- 추가납입
- Java
- 사망
- 파이썬
- 프로그래밍
- jQuery
- 납입
- python
- 웹개발
- Vue.js
- 특약
- 보험
- 심장질환
- PythonProgramming
- 수수료
- 교보생명
- 변환
- 뇌출혈
- 문자열
- 보험료
- 프론트엔드
- 가입
- 코딩
- 교보
- 자바스크립트
- 리스트
- 중도인출
Archives
- Today
- Total
SeouliteLab
[Java/자바] HashSet 정렬하는 3가지 방법 본문
HashSet 정렬 방법
Java의 HashSet은 정렬되지 않은 데이터를 저장하는데 유용한 컬렉션입니다. 하지만 때때로 정렬된 순서로 요소를 가져오고 싶을 때가 있습니다. 이번 글에서는 Java에서 HashSet을 정렬하는 세 가지 방법을 살펴보겠습니다.
1. TreeSet 사용
TreeSet은 정렬된 순서로 요소를 저장하는 Set 인터페이스의 구현체입니다. TreeSet에 요소를 추가하면 자동으로 정렬됩니다.
import java.util.*;
public class Main {
public static void main(String[] args) {
Set numbers = new TreeSet<>(Arrays.asList(3, 1, 2));
System.out.println("정렬된 HashSet: " + numbers);
}
}
출력:
정렬된 HashSet: [1, 2, 3]
2. ArrayList로 변환 후 정렬
HashSet을 ArrayList로 변환한 다음 Collections.sort() 메서드를 사용하여 정렬할 수 있습니다.
import java.util.*;
public class Main {
public static void main(String[] args) {
Set numbers = new HashSet<>(Arrays.asList(3, 1, 2));
List sortedNumbers = new ArrayList<>(numbers);
Collections.sort(sortedNumbers);
System.out.println("정렬된 HashSet: " + sortedNumbers);
}
}
출력:
정렬된 HashSet: [1, 2, 3]
3. Stream.sorted() 메서드 사용
Java 8 이상에서는 Stream.sorted() 메서드를 사용하여 HashSet을 정렬할 수 있습니다.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Set numbers = new HashSet<>(Arrays.asList(3, 1, 2));
List sortedNumbers = numbers.stream().sorted().collect(Collectors.toList());
System.out.println("정렬된 HashSet: " + sortedNumbers);
}
}
출력:
정렬된 HashSet: [1, 2, 3]
'프로그래밍' 카테고리의 다른 글
[Java/자바] ArrayList로 데이터 관리하기 (0) | 2024.03.09 |
---|---|
[Java/자바] 리스트 정렬하는 3가지 방법 (0) | 2024.03.08 |
[Java/자바] 리스트 정렬하는 3가지 방법 (0) | 2024.03.08 |
[Java/자바] 2차원 배열 선언 및 출력 방법 (0) | 2024.03.08 |
[Java/자바] HashSet.contains() 메서드 사용 예제 (0) | 2024.03.08 |