WEB开发网
开发学院WEB开发Jsp java开源类库pinyin4j的使用 阅读

java开源类库pinyin4j的使用

 2009-11-11 21:00:03 来源:WEB开发网   
核心提示:import java.util.Arrays;import java.util.Comparator;import java.util.List;import net.sourceforge.pinyin4j.PinyinHelper;public class PinyinComparator implements
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import net.sourceforge.pinyin4j.PinyinHelper;

public class PinyinComparator implements Comparator<Object> {

  PRivate String concatPinyinStringArray(String[] pinyinArray) {
    StringBuffer pinyinStrBuf = new StringBuffer();

    if ((null != pinyinArray) && (pinyinArray.length > 0)) {
      for (int i = 0; i < pinyinArray.length; i++) {
        pinyinStrBuf.append(pinyinArray[i]);
      }
    }
    String outputString = pinyinStrBuf.toString();
    return outputString;
  }

  public int compare(Object o1, Object o2) {

    int length1 = ((String) o1).length();
    int length2 = ((String) o2).length();

    int length = length1 - length2 > 0 ? length2 : length1;

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

      String c1topinyin = concatPinyinStringArray(PinyinHelper.toHanyuPinyinStringArray(c1));
      String c2topinyin = concatPinyinStringArray(PinyinHelper.toHanyuPinyinStringArray(c2));

      if ("".equals(c1topinyin) && "".equals(c2topinyin)) {
        if (c1 - c2 == 0) {
          continue;
        }
        else {
          return c1 - c2;
        }

      }
      else if ("".equals(c1topinyin) && !"".equals(c2topinyin)) {
        return -1;
      }
      else if (!"".equals(c1topinyin) && "".equals(c2topinyin)) {
        return 1;
      }
      else {
        int pinyinCompareValue = c1topinyin.compareTo(c2topinyin);
        if (pinyinCompareValue == 0) {
          if (c1 - c2 == 0) {
            continue;
          }
          else {
            //同音字按笔画比较 先不实现 
            return c1 - c2;
          }

        }
        return pinyinCompareValue;
      }
    }

    return length1 - length2;
  }

  public static void main(String[] args) {
    String[] data = { "13", "12", "123a", "1234", "123", "张a", "李四", "张a1", "章a", "9", "7", "镕", "C", "H", "张A", "重申", "重量" };
    List list = Arrays.asList(data);
    Arrays.sort(data, new PinyinComparator());
    System.out.println(list);
  }

}

测试结果:

[12, 123, 1234, 123a, 13, 7, 9, C, H, 李四, 镕, 张A, 张a, 张a1, 章a, 重量, 重申]

Tags:java 开源 pinyinj

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接