How to sort a HashSet?

后端 未结 19 2472
耶瑟儿~
耶瑟儿~ 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:24

    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);
    

提交回复
热议问题