对多个字符串(不重复)按照长度排序(由短到长)
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetDemo2 {
public static void main(String[] args) {
//对多个字符串(不重复)按照长度排序(由短到长)
/*
* 思路:
* 1.多个字符串,需要容器存储。
* 2.选择哪个容器呢? 数组?StringBuffer,StringBuilder? 集合
* 3.强调不重复,所以用Set集合
* 4.还需要排序,用TreeSet集合
*/
sortStringByLength();
}
public static void sortStringByLength(){
Set set = new TreeSet(new CoparatorByString());
set.add("haha");
set.add("abc");
set.add("zz");
set.add("nba");
set.add("xixixi");
for(Object o:set){
System.out.println(o);
}
}
}
class CoparatorByString implements Comparator{
@Override
public int compare(Object o1, Object o2) {
String s1 = (String)o1;
String s2 = (String)o2;
//比较长度
int temp=s1.length()-s2.length();
//长度相同再按照自电脑顺序排序
return temp==0?s1.compareTo(s2):temp;
}
}
练习2:对多个字符串(重复),按照长度排序
import java.util.Comparator;
public class TreeSetDemo3 {
public static void main(String[] args) {
/*
* 练习:对多个字符串(重复),按照长度排序
* 思路:
* 1.能使用TreeSet吗?不能
* 2.可以存储到数组,List.
*/
sortStringByLength2();
}
public static void sortStringByLength2() {
String[] str = {"nba","haha","abccc","zero","xixi","nba","cctv","zero"};
//使用比较器
//排序需要进行嵌套for循环
CoparatorByString2 com = new CoparatorByString2();
for(int x=0;x<str.length;x++){
for(int y=0;y<str.length;y++){
if(com.compare(str[x], str[y])>0){
swap(str,x,y);
}
}
}
for(String s:str){
System.out.println(s);
}
}
public static void swap(String[] str, int x, int y) {
String temp =null;
temp = str[x];
str[x]=str[y];
str[y]=temp;
}
}
class CoparatorByString2 implements Comparator{
@Override
public int compare(Object o1, Object o2) {
String s1 = (String)o1;
String s2 = (String)o2;
//比较长度
int temp=s2.length()-s1.length();
//长度相同再按照字典顺序排序
return temp==0?s2.compareTo(s1):temp;
}
}
关注我的微信公众号(曲健磊的个人随笔),观看更多精彩内容: