业务场景:

一个list集合,里面add了若干个实体类,针对该实体类排序的属性为String。

使用技术,自定义list排序(JDK自带),重写Comparator接口的compare方法,汉字转拼音技术:使用的pinyin4j。

 

pinyin4j官网地址:http://pinyin4j.sourceforge.net/

不想去官网下载的我这里也有,地址为:

//tempRateList 为需要进行自定义排序的集合,SpRate为该集合的实体类,riskName为排序的属性。

直接上方案:

1、导入pinyin4j-2.5.0.jar;

2、对自定义排序的类使用以下方法进行自定义排序;

 

[java] view plain copy

 
1. Collections.sort(tempRateList,new Comparator<SpRate>() {  
2. @Override  
3. public int compare(SpRate s1, SpRate s2) {  
4.         String o1 = s1.getRiskName();  
5.         String o2 = s2.getRiskName();  
6. for (int i = 0; i < o1.length() && i < o2.length(); i++) {  
7.   
8. int codePoint1 = o1.charAt(i);  
9. int codePoint2 = o2.charAt(i);  
10.   
11. if (Character.isSupplementaryCodePoint(codePoint1)  
12.             || Character.isSupplementaryCodePoint(codePoint2)) {  
13.         i++;  
14.         }  
15.   
16. if (codePoint1 != codePoint2) {  
17. if (Character.isSupplementaryCodePoint(codePoint1)  
18.             || Character.isSupplementaryCodePoint(codePoint2)) {  
19. return codePoint1 - codePoint2;  
20.         }  
21.   
22. char) codePoint1) == null   
23. null : PinyinHelper.toHanyuPinyinStringArray((char) codePoint1)[0];  
24. char) codePoint2) == null   
25. null : PinyinHelper.toHanyuPinyinStringArray((char) codePoint2)[0];  
26.   
27. if (pinyin1 != null && pinyin2 != null) { // 两个字符都是汉字  
28. if (!pinyin1.equals(pinyin2)) {  
29. return pinyin1.compareTo(pinyin2);  
30.             }  
31. else {  
32. return codePoint1 - codePoint2;  
33.         }  
34.         }  
35.     }  
36. return o1.length() - o2.length();  
37.     }  
38. });

3、方法结束后  tempRateList 对象就完成了自定义排序