How to sort a HashSet?

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

    If you want want the end Collection to be in the form of Set and if you want to define your own natural order rather than that of TreeSet then -

    1. Convert the HashSet into List
    2. Custom sort the List using Comparator
    3. Convert back the List into LinkedHashSet to maintain order
    4. Display the LinkedHashSet

    Sample program -

    package demo31;
    
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashSet;
    import java.util.LinkedHashSet;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Set;
    
    public class App26 {
        public static void main(String[] args) {
            Set set = new HashSet<>();
            addElements(set);
            List list = new LinkedList<>();
            list = convertToList(set);
            Collections.sort(list, new Comparator() {
                @Override
                public int compare(String s1, String s2) {
                    int flag = s2.length() - s1.length();
                    if(flag != 0) {
                        return flag;
                    } else {
                        return -s1.compareTo(s2);
                    }
                }
            });
            Set set2 = new LinkedHashSet<>();
            set2 = convertToSet(list);
            displayElements(set2);
        }
        public static void addElements(Set set) {
            set.add("Hippopotamus");
            set.add("Rhinocerous");
            set.add("Zebra");
            set.add("Tiger");
            set.add("Giraffe");
            set.add("Cheetah");
            set.add("Wolf");
            set.add("Fox");
            set.add("Dog");
            set.add("Cat");
        }
        public static List convertToList(Set set) {
            List list = new LinkedList<>();
            for(String element: set) {
                list.add(element);
            }
            return list;
        }
        public static Set convertToSet(List list) {
            Set set = new LinkedHashSet<>();
            for(String element: list) {
                set.add(element);
            }
            return set;
        }
        public static void displayElements(Set set) {
            System.out.println(set);
        }
    }
    

    Output -

    [Hippopotamus, Rhinocerous, Giraffe, Cheetah, Zebra, Tiger, Wolf, Fox, Dog, Cat]
    

    Here the collection has been sorted as -

    First - Descending order of String length
    Second - Descending order of String alphabetical hierarchy

提交回复
热议问题