Java自定义比较器Comparator
1.数字排序
奇数在前,偶数在后。奇数降序,偶数升序。输入:“0,1,2,3,4,5,6,7,8,9” 输出:"9,7,5,3,1,0,2,4,6,8"
package com.sheepmu.text; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /* * @author sheepmu */ public class HWCompetition { public static void main(String[] args){ String s="0,1,2,3,4,5,6,7,8,9"; System.out.println(getSort( s));//9 7 5 3 1 0 2 4 6 8 } public static String getSort(String s){ List<Integer>list=new ArrayList<Integer>(); String[] ss=s.split(","); for(int i=0;i<ss.length;i++){ list.add(Integer.parseInt(ss[i]+"") ); } Collections.sort(list, new Comparator<Integer>(){ @Override public int compare(Integer o1, Integer o2) { int result=0; if(o1%2==1&&o2%2==0){ result=o2%2- o1%2;// 结果为-才是前者在前 } // if(o1%2==0&&o2%2==1){//和上面同样的作用 // result=o2%2- o1%2;//+ // } if(o1%2==1&&o2%2==1){ result=o2-o1;//奇 降序 } if(o1%2==0&&o2%2==0){ result= o1-o2;//偶 升序 } return result; }} ); StringBuffer sb=new StringBuffer(); for(int i:list){ sb.append(i+" "); } return sb.toString(); } }2.域名排序
规则:mail.sheepmu.com从 右往左 分别是 顶级域名,一级域名,二级域名。比较时从顶级 域名开始比较,按字典顺序比较,顶级域名相同再比较一级域名.....若某个域名是一个域名的子集,比如sheepmu.com,则 sheepmu.com 在mail.sheepmu.com之前。
输入:{mail.sheepmu.com, sheepmu.com, hah.abc.org, cc.baidu.cn}
输出:{sheepmu.com, mail.sheepmu.com, cc.baidu.cn, hah.abc.org}
package com.sheepmu.text; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; /* * @author sheepmu */ public class HWCompetition { public static void main(String[] args){ String[] ss={"mail.sheepmu.com","sheepmu.com","hah.abc.org","cc.baidu.cn","bat.haha.ab"}; System.out.println(getSort(ss)); } public static String getSort(String[] ss){ List<String>list=new ArrayList<String>(); for(int i=0;i<ss.length;i++){ list.add(ss[i]); } Collections.sort(list, new Comparator<String>(){ @Override public int compare(String o1, String o2) { String[] ss1=o1.split("\\."); String[] ss2=o2.split("\\."); System.out.println(Arrays.toString(ss1)+" 和 "+Arrays.toString(ss2) ); int len=ss1.length<=ss2.length? ss1.length:ss2.length;//一定不要忘了等号,不然长度等的情况就悲剧了。循环比较时以短的为标准 int j=0; for(;j<len;j++){ if(!ss1[ss1.length-1-j].equals(ss2[ss2.length-1-j])){ System.out.println(" -某段不等-------->" ); return ss1[ss1.length-1-j].compareTo(ss2[ss2.length-1-j]); } } if(j==len){//循环完了 System.out.println(" -循环完了-------->"+len); return o1.length()-o2.length(); } return 0; }} ); StringBuffer sb=new StringBuffer(); for(String i:list){ sb.append(i+" "); } return sb.toString(); } }