Java에서 HashSet을 정렬하는 방법

HashSet은 요소의 순서를 유지하지 않지만 Collections.sort() 또는 요소를 TreeSet.

1) Collections.sort()

The method Collections.sort() 인터페이스를 구현하는 객체 컬렉션을 정렬할 수 있습니다 java.util.List. HashSet 요소를 ArrayList, LinkedList 또는 Vector.  가장 간단한 ArrayList 클래스를 사용하겠습니다.   다음으로
Collections.sort() />
import java.util.ArrayList; 
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

public class TriHashSet {

public static void main(String[] args) {
//해시 집합 만들기
HashSet< 문자열> hset = 새로운 HashSet< 문자열> ();

//요소 추가
hset.add("a2");
hset.add("a3");
hset.add("b1");
hset.add("b3");
hset.add("a1");
hset.add("b2");

System.out.println("정렬 전:");
for(문자열 s: hset)
System.out.println(s);

//HashSet 요소를 ArrayList
List에 복사합니다< 문자열> 목록 = 새로운 ArrayList< 문자열> (hset)입니다.
Collections.sort(목록);

System.out.println("정렬 후:");
for(문자열 s: hset)
System.out.println(s);
}
}
출력:

정렬 전: 
b1
a1
b3
b2
a2
a3
정렬 후:
b1
a1
b3
b2
a2
a3

1) TreeSet을 사용하여 HashSet 정렬

TreeSet을 사용하는 것은 매우 간단합니다. HashSet.

import java.util.HashSet 을 인수로 사용하여 TreeSet 인스턴스를 생성하십시오. 
import java.util.TreeSet;

public class TriHashSetTreeMap {

public static void main(String[] args) {
//해시 세트 생성
HashSet hset = new HashSet();

//요소 추가
hset.add(5);
hset.add(16);
hset.add(8);
hset.add(22);
hset.add(14);
hset.add(11);

System.out.println("정렬하기 전에: "+hset);
for(int n: hset)
System.out.println(n);

//HashSet 요소를 ArrayList
TreeSet treeset = new TreeSet< > (hset)입니다.

System.out.println("정렬 후: "+트리셋);
for(int n : 트리셋)
System.out.println(n);
}
}
출력:

정렬 전: [16, 5, 22, 8, 11, 14]
16
5
22
8
11
14
After IR : [5, 8, 11, 14, 16, 22]
5
8
11
14
16
22 < / pre>< / div>