[学习笔记]按中文名称排序

需要引入pinyin4j.jar

package com.skyland.util;

import java.util.Comparator;

import net.sourceforge.pinyin4j.PinyinHelper;



import com.skyland.webapp.auth.AuthUser;

public class CompareNamePinyin implements Comparator<Object>{

public int compare(Object obj1, Object obj2) {
//需要排序的对象
AuthUser dept1 = (AuthUser)obj1;
AuthUser dept2 = (AuthUser)obj2;
//需要排序的属性
String o1 =dept1.getName();
String o2 =dept2.getName();

for (int i = 0; i < o1.length() && i < o2.length(); i++) {
char c1 = o1.charAt(i);
char c2 = o2.charAt(i);

String pinyin1 = pinyin(c1);
String pinyin2 = pinyin(c2);

if (pinyin1 != null && pinyin2 != null) {

if (!pinyin1.equals(pinyin2)) {
return pinyin1.compareTo(pinyin2);
}
} else {
if (c1 != c2) {
return c1 - c2;
}
}
}

return o1.length() - o2.length();
}

private String pinyin(char c) {
//返回该字的汉语拼音数字,如“王”字返回:[wang2, wang4]
// 说明该字有两种读法,分别为wang2,第二声,wang4,第四声
String[] a = PinyinHelper.toHanyuPinyinStringArray(c);
if (a == null){
return null;
}
return a[0];
}


}

你可能感兴趣的:([学习笔记]按中文名称排序)