📜  如何在Java中对 HashSet 进行排序

📅  最后修改于: 2022-05-13 01:55:09.401000             🧑  作者: Mango

如何在Java中对 HashSet 进行排序

在Java中给定一个 HashSet,任务是对这个 HashSet 进行排序。

例子:

Input: HashSet: [Geeks, For, ForGeeks, GeeksforGeeks]
Output: [For, ForGeeks, Geeks, GeeksforGeeks]

Input: HashSet: [2, 5, 3, 1, 4]
Output: [1, 2, 3, 4, 5] 

HashSet 类实现了 Set 接口,由一个哈希表支持,该哈希表实际上是一个 HashMap 实例。不保证集合的迭代顺序,这意味着该类不保证元素随时间的恒定顺序。

这意味着 HashSet 不维护其元素的顺序。因此 HashSet 的排序是不可能的。

但是HashSet的元素可以通过转换成List或者TreeSet的方式间接排序,但是这样会将元素保留在目标类型而不是HashSet类型。

下面是上述方法的实现:

程序1:通过将HashSet转换为List。

// Java program to sort a HashSet
  
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
        // Creating a HashSet
        HashSet set = new HashSet();
  
        // Adding elements into HashSet using add()
        set.add("geeks");
        set.add("practice");
        set.add("contribute");
        set.add("ide");
  
        System.out.println("Original HashSet: "
                           + set);
  
        // Sorting HashSet using List
        List list = new ArrayList(set);
        Collections.sort(list);
  
        // Print the sorted elements of the HashSet
        System.out.println("HashSet elements "
                           + "in sorted order "
                           + "using List: "
                           + list);
    }
}
输出:
Original HashSet: [practice, geeks, contribute, ide]
HashSet elements in sorted order using List: [contribute, geeks, ide, practice]

程序2:通过将HashSet转换为TreeSet。

// Java program to sort a HashSet
  
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Creating a HashSet
        HashSet set = new HashSet();
  
        // Adding elements into HashSet using add()
        set.add("geeks");
        set.add("practice");
        set.add("contribute");
        set.add("ide");
  
        System.out.println("Original HashSet: "
                           + set);
  
        // Sorting HashSet using TreeSet
        TreeSet treeSet = new TreeSet(set);
  
        // Print the sorted elements of the HashSet
        System.out.println("HashSet elements "
                           + "in sorted order "
                           + "using TreeSet: "
                           + treeSet);
    }
}
输出:
Original HashSet: [practice, geeks, contribute, ide]
HashSet elements in sorted order using TreeSet: [contribute, geeks, ide, practice]