How to sort a HashSet?

后端 未结 19 2402
耶瑟儿~
耶瑟儿~ 2020-12-02 12:42

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

相关标签:
19条回答
  • 2020-12-02 13:25

    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]
    
    0 讨论(0)
  • 2020-12-02 13:27

    SortedSet has been added Since java 7 https://docs.oracle.com/javase/8/docs/api/java/util/SortedSet.html

    0 讨论(0)
  • 2020-12-02 13:28

    You can use a TreeSet instead.

    0 讨论(0)
  • 2020-12-02 13:33

    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");
    
    0 讨论(0)
  • 2020-12-02 13:34

    You can use Java 8 collectors and TreeSet

    list.stream().collect(Collectors.toCollection(TreeSet::new))

    0 讨论(0)
  • 2020-12-02 13:36

    Just in-case you don't wanna use a TreeSet you could try this.

    set = set.stream().sorted().collect(Collectors.toCollection(LinkedHashSet::new));
    
    0 讨论(0)
提交回复
热议问题