我是靠谱客的博主 无辜火,这篇文章主要介绍Java使用Collections.sort对中文进行排序方式,现在分享给大家,希望可以做个参考。

使用Collections.sort对中文进行排序

使用collections.sort(List list, Comparator <? super T>)对中文名字进行排序

调用Collator的静态方法getInstance来获取所需语言环境

核心代码:

下面展示 核心代码。

复制代码
1
result= Collator.getInstance(Locale.CHINA).compare(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).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}] } }

Collections.sort 排序 注解

逆序:

以上为个人经验,希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是无辜火最近收集整理的关于Java使用Collections.sort对中文进行排序方式的全部内容,更多相关Java使用Collections内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(122)

评论列表共有 0 条评论

立即
投稿
返回
顶部