代码分享:
package com.ethjava; //hashSet实现排序 //treeSet实现倒序 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的遍历 for(String s:hashSet){ System.out.print(s+" "); } System.out.println(); //aaa ccc bbb zzz Set<String> treeSet=new TreeSet<>(); treeSet.addAll(hashSet); // 对于set来说,是将c中所有元素添加到一个Set中,如果Set中已有某一元素,则不添加,因Set不允许有重复值 for(String s:treeSet){ System.out.print(s+" "); } System.out.println();//自动是升序 //aaa bbb ccc zzz //下面实现倒序排列 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 //实现倒序输出 //第二种实现倒序输出的方式 ArrayList<String> arrayList=new ArrayList<>(); for(String s:hashSet){ arrayList.add(s); } Collections.sort(arrayList); //遍历arrayList for(int i=0;i<arrayList.size();i++){ System.out.print(arrayList.get(i)+" "); } System.out.println(); //aaa bbb ccc zzz //升序排序 //下面是降序排序 Collections.sort(arrayList,new Comparator<String>(){ public int compare(String o1,String o2){ return o2.compareTo(o1); } }); //遍历arrayList for(int i=0;i<arrayList.size();i++){ System.out.print(arrayList.get(i)+" "); } //zzz ccc bbb aaa //倒序输出 } }