Java 如何对HashSet进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22391350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:29:19  来源:igfitidea点击:

How to sort a HashSet?

javasortingcollectionssethashset

提问by Diana

For lists, we use the Collections.sort(List)method. What if we want to sort a HashSet?

对于列表,我们使用Collections.sort(List)方法。如果我们想对 a 进行排序HashSet怎么办?

回答by jcarvalho

You can use a TreeSetinstead.

您可以改用TreeSet

回答by P45 Imminent

Use java.util.TreeSetas the actual object. When you iterate over this collection, the values come back in a well-defined order.

使用java.util.TreeSet作为实际的对象。当您迭代此集合时,值会以明确定义的顺序返回。

If you use java.util.HashSetthen the order depends on an internal hash function which is almost certainly not lexicographic (based on content).

如果使用,java.util.HashSet则顺序取决于内部散列函数,该函数几乎可以肯定不是按字典顺序排列的(基于内容)。

回答by isak gilbert

A HashSet does not guarantee any order of its elements. If you need this guarantee, consider using a TreeSet to hold your elements.

HashSet 不保证其元素的任何顺序。如果您需要这种保证,请考虑使用 TreeSet 来保存您的元素。

However if you just need your elements sorted for this one occurrence, then just temporarily create a List and sort that:

但是,如果您只需要针对此事件对元素进行排序,则只需临时创建一个 List 并对其进行排序:

Set<?> yourHashSet = new HashSet<>();

...

List<?> sortedList = new ArrayList<>(yourHashSet);
Collections.sort(sortedList);

回答by Abdullah Khan

Add all your objects to the TreeSet, you will get a sorted Set. Below is a raw example.

将所有对象添加到 中TreeSet,您将获得一个排序的 Set。下面是一个原始示例。

HashSet myHashSet = new HashSet();
myHashSet.add(1);
myHashSet.add(23);
myHashSet.add(45);
myHashSet.add(12);

TreeSet myTreeSet = new TreeSet();
myTreeSet.addAll(myHashSet);
System.out.println(myTreeSet); // Prints [1, 12, 23, 45]

回答by Glenn Strycker

This simple command did the trick for me:

这个简单的命令对我有用:

myHashSet.toList.sorted

I used this within a print statement, so if you need to actually persist the ordering, you may need to use TreeSets or other structures proposed on this thread.

我在 print 语句中使用了它,因此如果您需要实际保留排序,则可能需要使用 TreeSets 或此线程上提出的其他结构。

回答by off99555

Elements in HashSet can't be sorted. Whenever you put element into HashSet, it will mess up the ordering of the whole set. It does that for performance. When you don't care about the order, HashSet will be the most efficient set for fast insertion and search.

HashSet 中的元素无法排序。每当您将元素放入 HashSet 时,它都会弄乱整个集合的顺序。它这样做是为了性能。当你不关心顺序时,HashSet 将是最有效的快速插入和搜索的集合。

TreeSet will sort all the elements automatically every time you insert an element.

每次插入元素时,TreeSet 都会自动对所有元素进行排序。

Perhaps, what you are trying to do is to sort just once. In that case, TreeSet is not the best option because it needs to determine the placing of newly added elements all the time.

也许,您要做的只是排序一次。在这种情况下,TreeSet 不是最佳选择,因为它需要始终确定新添加元素的放置位置。

The most efficient solution is to use ArrayList. Create a new list and add all the elements then sort it once. If you want to retain only unique elements (remove all duplicates like set does, then put the list into a LinkedHashSet, it will retain the order you have already sorted)

最有效的解决方案是使用 ArrayList。创建一个新列表并添加所有元素,然后对其进行一次排序。如果您只想保留唯一元素(像 set 一样删除所有重复项,然后将列表放入 LinkedHashSet,它将保留您已经排序的顺序)

List<Integer> list = new ArrayList<>();
list.add(6);
list.add(4);
list.add(4);
list.add(5);
Collections.sort(list);
Set<Integer> unique = new LinkedHashSet<>(list); // 4 5 6
// The above line is not copying the objects! It only copies references.

Now, you've gotten a sorted set if you want it in a list form then convert it into list.

现在,如果您希望以列表形式将其转换为列表,则您已经获得了一个排序集。

回答by Sujit

you can do this in the following ways:

您可以通过以下方式执行此操作:

Method 1:

方法一:

  1. Create a list and store all the hashset values into it
  2. sort the list using Collections.sort()
  3. Store the list back into LinkedHashSet as it preserves the insertion order
  1. 创建一个列表并将所有哈希集值存储到其中
  2. 使用 Collections.sort() 对列表进行排序
  3. 将列表存储回 LinkedHashSet 因为它保留了插入顺序

Method 2:

方法二:

  • Create a treeSet and store all the values into it.
  • 创建一个 treeSet 并将所有值存储到其中。

Method 2 is more preferable because the other method consumes lot of time to transfer data back and forth between hashset and list.

方法 2 更可取,因为另一种方法在 hashset 和 list 之间来回传输数据会消耗大量时间。

回答by Alisa

You can use TreeSet as mentioned in other answers.

您可以使用其他答案中提到的 TreeSet 。

Here's a little more elaboration on how to use it:

这里有一些关于如何使用它的详细说明:

TreeSet<String> ts = new TreeSet<String>();
ts.add("b1");
ts.add("b3");
ts.add("b2");
ts.add("a1");
ts.add("a2");
System.out.println(ts);
for (String s: ts)
    System.out.println(s);

Output:

输出:

[a1, a2, a3, a4, a5]
a1
a2
b1
b2
b3

回答by Ved Prakash

1. Add all set element in list -> al.addAll(s);
2. Sort all the elements in list using -> Collections.sort(al);


 public class SortSetProblem {
 public static void main(String[] args) {
    ArrayList<String> al = new ArrayList();
    Set<String> s = new HashSet<>();
    s.add("ved");
    s.add("prakash");
    s.add("sharma");
    s.add("apple");
    s.add("ved");
    s.add("banana");
    System.out.println("Before Sorting");
    for (String s1 : s) {
        System.out.print("  " + s1);
    }

    System.out.println("After Sorting");
    al.addAll(s);
    Collections.sort(al);
    for (String set : al) {
        System.out.print(" " + set);
    }
  }
 }

input - ved prakash sharma apple ved banana

Output - apple banana prakash sharma ved

输入 - ved prakash sharma 苹果 ved 香蕉

输出 - 苹果香蕉 prakash sharma ved

回答by Ankita Bhowmik

You can use guava library for the same

您可以将番石榴库用于相同的

Set<String> sortedSet = FluentIterable.from(myHashSet).toSortedSet(new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        // descending order of relevance
        //required code
    }
});