package XXXXXXXX;
import net.sourceforge.pinyin4j.PinyinHelper;
import java.util.Comparator;
public class PinyinComparator implements Comparator<String> {
public int compare(String o1, String o2) {
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];
}
}
使用方法
/**
* 默认降序
*/
private void filedSort3(String fieldName, List<ListMaterialByEquipmentDTO> list) {
switch (fieldName) {
case "materialName":
list.sort((ListMaterialByEquipmentDTO o1, ListMaterialByEquipmentDTO o2) -> new PinyinComparator().compare(o1.getMaterialName(), o2.getMaterialName()));
break;
// case "grade":
// list.sort((arg0, arg1) -> (arg1.getGrade() == null ? BigDecimal.ZERO : arg1.getGrade()).compareTo(arg0.getGrade() == null ? BigDecimal.ZERO : arg0.getGrade()));
// break;
default:
break;
}
}
调用
List<ListMaterialByEquipmentDTO> typeList =Lists.newArraylist();
filedSort3("materialName", typeList);
使用场景为需要对比排序数字大小.或者按照名字等进行a-z排序的时候可以用到
网友评论