How to sort a HashSet?

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

    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 sortedListOfFoo =

提交回复
热议问题