HashSet achieve the sort of two ways

Code Share:

package com.ethjava;
// hashSet implement sorting
// treeSet achieve reverse
import java.util. *;

public class setPaixu {
    public static void main(String[] args){
        Set<String> hashSet=new HashSet<>();
        hashSet.add("aaa");
        hashSet.add("ccc");
        hashSet.add("zzz");
        hashSet.add("bbb");
        // hashSet traversal
        for(String s:hashSet){
            System.out.print(s+" ");
        }
        System.out.println();
        //aaa ccc bbb zzz

        Set<String> treeSet=new TreeSet<>();
        treeSet.addAll(hashSet);
        // For the set, is to add all the elements of c into a Set, Set if already an element, not add, duplicate values ​​are not allowed because Set
        for(String s:treeSet){
            System.out.print(s+" ");
        }
        System.out.println (); // automatic ascending
        //aaa bbb ccc zzz


        // achieved following the reverse order

        Set<String> treeSet2=new TreeSet<String>(new Comparator<String>(){
            public int compare(String o1,String o2){
                return o2.compareTo(o1);
            }
        });
        treeSet2.addAll(hashSet);
        for(String s:treeSet2){
            System.out.print(s+" ");
        }
        System.out.println();
        ///zzz ccc bbb aaa
        // achieve reverse output

        // The second way to achieve reverse output
        ArrayList<String> arrayList=new ArrayList<>();
        for(String s:hashSet){
           arrayList.add(s);
        }
        Collections.sort(arrayList);
        // Traverse arrayList
        for(int i=0;i<arrayList.size();i++){
            System.out.print(arrayList.get(i)+" ");
        }
        System.out.println();
        //aaa bbb ccc zzz
        // ascending order

        // Here is sorted in descending order

        Collections.sort(arrayList,new Comparator<String>(){
            public int compare(String o1,String o2){
                 return o2.compareTo(o1);
            }
        });
        // Traverse arrayList
        for(int i=0;i<arrayList.size();i++){
            System.out.print(arrayList.get(i)+" ");
        }
        //zzz ccc bbb aaa
        // reverse output














    }
}
Published 45 original articles · won praise 8 · views 5862

Guess you like

Origin blog.csdn.net/wenyunick/article/details/103462814