代码分享:
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
//倒序输出
}
}

本文深入探讨了Java中HashSet和TreeSet的使用,展示了如何利用TreeSet实现字符串集合的升序和降序排序,并通过自定义Comparator实现了倒序排列。同时,文章还介绍了ArrayList结合Collections.sort方法进行升序和降序排序的技巧。
1843

被折叠的 条评论
为什么被折叠?



