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 = new 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 にコピーします<文字列>list = new ArrayListです<文字列>(hset);
Collections.sort(list);
System.out.println("ソート後:");
for(文字列s:hset)
System.out.println(s);
}
}
並べ替え前:
b1
a1
b3
b2
a2
a3
並べ替え後:
b1
a1
b3
b2
a2
a3
import java.util.HashSet を引数として TreeSet のインスタンスを作成するだけです。出力:
import java.util.TreeSet;
public class TriHashSetTreeMap {
public static void main(String[] args) {
//ハッシュセット
HashSethset = 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 にコピーします
TreeSettreeset = new TreeSet<>(hset);
System.out.println("並べ替え後: "+treeset);
for(int n : treeset)
System.out.println(n);
}
}
並べ替え前: [16, 5, 22, 8, 11, 14]
16
5
22
8
11
14
AfterIR: [5, 8, 11, 14, 16, 22]
5
8
11
14
16
22
Please disable your ad blocker and refresh the window to use this website.