How to sort a HashSet?

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

    Based on the answer given by @LazerBanana i will put my own example of a Set sorted by the Id of the Object:

    Set yourSet = [...];
    
    yourSet.stream().sorted(new Comparator() {
        @Override
        public int compare(Clazz o1, Clazz o2) {
            return o1.getId().compareTo(o2.getId());
        }
    }).collect(Collectors.toList()); // Returns the sorted List (using toSet() wont work)
    

提交回复
热议问题