使用Collections.sort对中文进行排序
使用collections.sort(List list, Comparator <? super T>)对中文名字进行排序
调用Collator的静态方法getInstance来获取所需语言环境
核心代码:
下面展示 核心代码。
1 |
result= Collator.getInstance(Locale.CHINA)测试数据pare(o1.getName(), o2.getName()); |
全部代码,里面有对数字的排序方法,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
public class Demo03Sort { public static void main(String[] args) { ArrayList<Integer> list01 = new ArrayList<>(); list01.add( 1 ); list01.add( 4 ); list01.add( 3 ); System.out.println(list01); //[1, 4, 3] Collections.sort(list01, new Comparator<Integer>() { //重写比较的规则 @Override public int compare(Integer o1, Integer o2) { //return o2 - o1;//降序排序 return o1 - o2; //升序排序 } }); System.out.println(list01); //[1, 3, 4] ArrayList<Student> list02 = new ArrayList<>(); list02.add( new Student( "萧炎" , 22 )); list02.add( new Student( "萧薰" , 20 )); list02.add( new Student( "萧玉" , 24 )); list02.add( new Student( "阿玉" , 22 )); System.out.println(list02); //[Student{name='萧炎', age=22}, Student{name='萧薰', age=20}, Student{name='萧玉', age=24}] Collections.sort(list02, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { //按照年龄升序排序 int result = o1.getAge() - o2.getAge(); //如果两人的年龄相同,在使用姓名的第一个字比较 if (result == 0 ){ //result = o1.getName().charAt(0) - o2.getName().charAt(0); //按照中文名称排序 result= Collator.getInstance(Locale.CHINA)测试数据pare(o1.getName(), o2.getName()); } return result; } }); System.out.println(list02); //未按照中文排序的结果:[Student{name='萧薰', age=20}, Student{name='萧炎', age=22}, Student{name='阿玉', age=22}, Student{name='萧玉', age=24}] //按照中文排序的结果:[Student{name='萧薰', age=20}, Student{name='阿玉', age=22}, Student{name='萧炎', age=22}, Student{name='萧玉', age=24}] } } |
Collections.sort 排序 注解
逆序:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/weixin_44246836/article/details/107250479/
查看更多关于Java使用Collections.sort对中文进行排序方式的详细内容...