如何在 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 elements
"+ hashSet);       Set<String> treeSet = new TreeSet<String>(hashSet);       System.out.println("Sorted elements
"+ treeSet);    } }

輸出

HashSet elements
[red, orange, green, blue, cyan]
Sorted elements
[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 elements
"+ hashSet);       List<String> myList = new ArrayList<String>(hashSet);       Collections.sort(myList,Collections.reverseOrder());       System.out.println("Sorted (descending order)
"+ myList);    } }

輸出

HashSet elements
[orange, green, blue, yellow, cyan]
Sorted (descending order)
[yellow, orange, green, cyan, blue]

更新於: 20-9-2019

1 千+ 次瀏覽

開啟您的職業生涯

完成課程,獲得認證

開始
廣告