Java 如何对HashSet进行排序 |
您所在的位置:网站首页 › 如何用java输入数字排序 › Java 如何对HashSet进行排序 |
Java 如何对HashSet进行排序
在Java中给定一个HashSet,任务是对这个HashSet进行排序。 例子。 输入: HashSet: [Geeks, For, ForGeeks, GeeksforGeeks] 输出: [For, ForGeeks, Geeks, GeeksforGeeks] 输入: HashSet: [2, 5, 3, 1, 4] 输出: [1, 2, 3, 4, 5] 建议:请先在{IDE} 上尝试你的方法,然后再继续解决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] |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |