- 博客分类:
好久没有写博客了,期间在做桌面云,被要求保密哈。不过最近在写一个android程序,需要实现一个中英文混合排序。不说了,直接代码;
HanYuUtil.java
HanYuUtil.java
伦理片 http://www.dotdy.com/
- import net.sourceforge.pinyin4j.PinyinHelper;
- import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
- import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
- import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
- import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
- import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
- public class HanYuUtil {
- /**
- * 将单个字符(包括单个汉字或者单个英文字母)转换为小写字母
- * @param c
- * @return
- */
- public String getCharacterPinYin(char c)
- {
- String[] pinyin=null;
- HanyuPinyinOutputFormat format =new HanyuPinyinOutputFormat();
- format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
- format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//汉字没有声调
- format.setVCharType(HanyuPinyinVCharType.WITH_V);
- try{
- pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
- }catch(BadHanyuPinyinOutputFormatCombination e){
- e.printStackTrace();
- }
- // 如果c不是汉字,toHanyuPinyinStringArray会返回null
- if (pinyin == null)
- return ((Character)c).toString().toLowerCase();
- // 只取一个发音,如果是多音字,仅取第一个发音
- return pinyin[0];
- }
- /**
- * 将包含中英文的字符串以小写英文字母的形式返回
- * @param str
- * @return
- */
- public String getStringPinYin(String str)
- {
- StringBuilder sb = new StringBuilder();
- String tempPinyin = null;
- for (int i = 0; i < str.length(); ++i)
- {
- tempPinyin = getCharacterPinYin(str.charAt(i));
- sb.append(tempPinyin);
- }
- return sb.toString();
- }
- }
CustomerComparator.java
- import java.util.Comparator;
- import com.xyz.kjy.db.Customer;
- public class CustomerComparator implements Comparator<Customer> {
- @Override
- public int compare(Customer customer0, Customer customer1) {
- // 按照商家名称排序
- String catalog0 = "";
- String catalog1 = "";
- if(customer0!=null&&customer0.getStoreName()!=null)
- catalog0=HanYuUtil.getStringPinYin(customer0.getStoreName());
- if(customer1!=null&&customer1.getStoreName()!=null)
- catalog1=HanYuUtil.getStringPinYin(customer1.getStoreName());
- return catalog0.compareTo(catalog1);
- }
- }
影音先锋电影 http://www.iskdy .com/
Customer.java
- public class Customer {
- private String storeName;//店名,唯一
- public String getStoreName() {
- return storeName;
- }
- public void setStoreName(String storeName) {
- this.storeName = storeName;
- }
- }
这里面用到了一个第三方的包,在附件