java arraylist 自定义排序(刚学java没搞懂自定义排序,举个例子问一下)在线等挺急的 例子在下面 5
一个arraylist"癸","乙","辛","丙","甲","壬","戊","己","丁","庚"要求排序排成原本的天干顺序...
一个arraylist "癸","乙","辛","丙","甲","壬","戊","己","丁","庚"
要求排序排成原本的天干顺序 展开
要求排序排成原本的天干顺序 展开
2个回答
展开全部
import java.util.*;
public class Example{
public static void main(String arg[]){
ArrayList<String> st = new ArrayList<String>(Arrays.asList(("癸,乙,辛,丙,甲,壬,戊,己,丁,庚").split(",")));
for(String i:st)
System.out.format("%s",i);
System.out.format("\n");
Collections.sort(st,new Comparator<String>(){
String Template = "甲乙丙丁戊己庚辛壬癸";
public int compare(String s1, String s2){
return (Template.indexOf(s1)>Template.indexOf(s2))?1:-1;
}
});
for(String i:st)
System.out.format("%s",i);
}
}
自定义排序,这里用的是重写comparator
展开全部
/**
* 自定义排序规则,实现Comparator接口
*/
class CustomComparator implements Comparator<String> {
private final Map<String, Integer> map = new HashMap<String, Integer>() {{
put("甲", 0);put("乙", 1);put("丙", 2);put("丁", 3);
put("戊", 4);put("己", 5);put("庚", 6);put("辛", 7);
put("壬", 8);put("癸", 9);
}
};
@Override
public int compare(String o1, String o2) {
if (o1 == o2) return 0;
if (o1 == null) return -1;
if (o2 == null) return 1;
if (map.get(o1) > map.get(o2)) return 1;
return -1;
}
}
@Test
public void testCustomComparator(){
String sa[]=new String[]{"癸","乙","辛","丙","甲","壬","戊","己","丁","庚"};
List<String> list=new ArrayList<>(Arrays.asList(sa));
Collections.sort(list,new CustomComparator());
for(String item:list) System.out.print(item+" ");
System.out.println();
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询