Java如何对HashSet进行排序
要在Java中对HashSet进行排序,可以使用另一个TreeSet类。
以下是在Java中对HashSet进行排序的代码-
示例
import java.util.*;
public class Main {
public static void main(String args[]) {
Set<String> hashSet = new HashSet<String>();
hashSet.add("green");
hashSet.add("blue");
hashSet.add("red");
hashSet.add("cyan");
hashSet.add("orange");
hashSet.add("green");
System.out.println("HashSet 元素\n"+ hashSet);
Set<String> treeSet = new TreeSet<String>(hashSet);
System.out.println("已排序的元素\n"+ treeSet);
}
}输出结果
HashSet 元素 [red, orange, green, blue, cyan] 已排序的元素 [blue, cyan, green, orange, red]
让我们看另一个示例,其中我们将使用Collections.sort()方法和reverseOrder()方法对HashSet进行降序排序-
示例
import java.util.*;
public class Main {
public static void main(String args[]) {
Set<String> hashSet = new HashSet<String>();
hashSet.add("yellow");
hashSet.add("green");
hashSet.add("blue");
hashSet.add("cyan");
hashSet.add("orange");
hashSet.add("green");
System.out.println("HashSet 元素\n"+ hashSet);
List<String> myList = new ArrayList<String>(hashSet);
Collections.sort(myList,Collections.reverseOrder());
System.out.println("已排序(降序)\n"+ myList);
}
}输出结果
HashSet 元素 [orange, green, blue, yellow, cyan] 已排序(降序) [yellow, orange, green, cyan, blue]
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬