How to sort HashSet in Java

How to sort HashSet in Java

Method One: By Converting HashSet to List

方法二:By Converting HashSet to TreeSet

import java.util.*;

public class HashSortOfSort {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("geeks");
        set.add("practice");
        set.add("contribute");
        set.add("ide");
        System.out.println(set);
        List<String> list1 = new ArrayList<>(set);
        Collections.sort(list1);
        System.out.println(list1);

        SortedSet<String> sortedSet = new TreeSet<>(set);
        System.out.println(sortedSet);
    }
}

[practice, geeks, contribute, ide]
[contribute, geeks, ide, practice]
[contribute, geeks, ide, practice]

Guess you like

Origin www.cnblogs.com/hglibin/p/11404292.html