package com.anyitzy.web;
import java.util.Comparator;
import net.sourceforge.pinyin4j.PinyinHelper;
import com.anyitzy.web.entity.train.Train;
@SuppressWarnings("rawtypes")
public class PinyinComparator implements Comparator {
public int compare(Object obj1,Object obj2) {
Train e1=(Train)obj1;
Train e2=(Train)obj2;
String o1=e1.getName();
String o2=e2.getName();
for (int i = 0; i < o1.length() && i < o2.length(); i++) {
int codePoint1 = o1.charAt(i);
int codePoint2 = o2.charAt(i);
if (Character.isSupplementaryCodePoint(codePoint1)
|| Character.isSupplementaryCodePoint(codePoint2)) {
i++;
}
if (codePoint1 != codePoint2) {
if (Character.isSupplementaryCodePoint(codePoint1)
|| Character.isSupplementaryCodePoint(codePoint2)) {
return codePoint1 - codePoint2;
}
String pinyin1 = pinyin((char) codePoint1);
String pinyin2 = pinyin((char) codePoint2);
if (pinyin1 != null && pinyin2 != null) { // 两个字符都是汉字
if (!pinyin1.equals(pinyin2)) {
return pinyin1.compareTo(pinyin2);
}
} else {
return codePoint1 - codePoint2;
}
}
}
return o1.length() - o2.length();
}
/**
* 字符的拼音,多音字就得到第一个拼音。不是汉字,就return null。
*/
private String pinyin(char c) {
String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(c);
if (pinyins == null) {
return null;
}
return pinyins[0];
}
}
package com.anyitzy.web;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.anyitzy.web.PinyinComparator;
import com.anyitzy.web.entity.train.Train;
public class PinyinComparatorTest {
public static void main(String[] args) {
List list=new ArrayList();
{
Train t=new Train();
t.setName("土工结构与边坡防护");
list.add(t);
}
{
Train t=new Train();
t.setName("地基处理");
list.add(t);
}
{
Train t=new Train();
t.setName("地震工程");
list.add(t);
}
{
Train t=new Train();
t.setName("基坑工程与地下工程");
list.add(t);
}
{
Train t=new Train();
t.setName("岩土工程勘察");
list.add(t);
}
{
Train t=new Train();
t.setName("岩土工程检测与监测、工程经济与管理");
list.add(t);
}
{
Train t=new Train();
t.setName("岩土工程设计基本原则、浅基础");
list.add(t);
}
{
Train t=new Train();
t.setName("特殊条件下的岩土工程");
list.add(t);
}
PinyinComparator comparator = new PinyinComparator();
Collections.sort(list, comparator) ;
for(Train t:list){
System.out.println(t.getName()+"==");
}
}
}