How to sort HashSet in Java

How to sort HashSet in Java

方法一: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]

上一篇:dp practice 1


下一篇:PAT (Basic Level) Practice (中文) 1002 写出这个数