Python 官方文档:入门教程 => 点击学习
目录使用Collections.sort对中文进行排序Collections.sort 排序 注解使用Collections.sort对中文进行排序 使用collections.so
使用collections.sort(List list, Comparator <? super T>)对中文名字进行排序
调用Collator的静态方法getInstance来获取所需语言环境
核心代码:
下面展示 核心代码。
result= Collator.getInstance(Locale.CHINA).compare(o1.getName(), o2.getName());
全部代码,里面有对数字的排序方法,
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).compare(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}]
}
}
逆序:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: Java使用Collections.sort对中文进行排序方式
本文链接: https://www.lsjlt.com/news/156711.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0