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条回答
The star\"
2楼-- · 2019-01-17 02:40

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

Method 2:

  • Create a treeSet and store all the values into it.

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

查看更多
女痞
3楼-- · 2019-01-17 02:44
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

查看更多
走好不送
4楼-- · 2019-01-17 02:48

Java 8 way to sort it would be:

fooHashSet.stream()
  .sorted(Comparator.comparing(Foo::getSize)) //comparator - how you want to sort it
  .collect(Collectors.toList()); //collector - what you want to collect it to

*Foo::getSize it's an example how to sort the HashSet of YourItem's naturally by size.

*Collectors.toList() is going to collect the result of sorting into a List the you will need to capture it with List<Foo> sortedListOfFoo =

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-17 02:52

In my humble opinion , LazerBanana's answer should be the top rated answer & accepted because all the other answers pointing to java.util.TreeSet ( or first convert to list then call Collections.sort(...) on the converted list ) didn't bothered to ask OP as what kind of objects your HashSet has i.e. if those elements have a predefined natural ordering or not & that is not optional question but a mandatory question.

You just can't go in & start putting your HashSet elements into a TreeSet if element type doesn't already implement Comparable interface or if you are not explicitly passing Comparator to TreeSet constructor.

From TreeSet JavaDoc ,

Constructs a new, empty tree set, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the add call will throw a ClassCastException.

That is why only all Java8 stream based answers - where you define your comparator on the spot - only make sense because implementing comparable in POJO becomes optional. Programmer defines comparator as and when needed. Trying to collect into TreeSet without asking this fundamental question is also incorrect ( Ninja's answer). Assuming object types to be String or Integer is also incorrect.

Having said that, other concerns like ,

  1. Sorting Performance
  2. Memory Foot Print ( retaining original set and creating new sorted sets each time sorting is done or wish to sort the set in - place etc etc )

should be the other relevant points too. Just pointing to API shouldn't be only intention.

Since Original set already contains only unique elements & that constraint is also maintained by sorted set so original set needs to be cleared from memory since data is duplicated.

查看更多
倾城 Initia
6楼-- · 2019-01-17 02:53

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

If you use java.util.HashSet then the order depends on an internal has function with more than likely is not lexographic.

查看更多
仙女界的扛把子
7楼-- · 2019-01-17 02:59

You can use a TreeSet instead.

查看更多
登录 后发表回答