How to sort a HashSet?

2019-01-17 02:02发布

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

14条回答
我想做一个坏孩纸
2楼-- · 2019-01-17 03:00

We can not decide that the elements of a HashSet would be sorted automatically. But we can sort them by converting into TreeSet or any List like ArrayList or LinkedList etc.

// Create a TreeSet object of class E
TreeSet<E> ts = new TreeSet<E> ();

// Convert your HashSet into TreeSet
ts.addAll(yourHashSet);

System.out.println(ts.toString() + "\t Sorted Automatically");
查看更多
爷的心禁止访问
3楼-- · 2019-01-17 03:00

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
    }
});
查看更多
Anthone
4楼-- · 2019-01-17 03:02

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.

查看更多
女痞
5楼-- · 2019-01-17 03:04

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

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]
查看更多
Fickle 薄情
6楼-- · 2019-01-17 03:05

Elements in HashSet can't be sorted. Whenever you put element into HashSet, it will mess up the whole buckets. The good thing about it is efficiency in performance.

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

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 new added elements all the time.

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)

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.

查看更多
我只想做你的唯一
7楼-- · 2019-01-17 03:05

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

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

Set yourHashSet = new HashSet();

...

List sortedList = new ArrayList(yourHashSet);
Collections.sort(sortedList);
查看更多
登录 后发表回答