select 下拉列表内容按拼音排序

    今天客户提出一个需求:就是让下拉框的内容按拼音排序,本人就从网上找了一个例子,也已经验证通过,故分享一下!

     首先在网上下载一个:pinyin4j-2.5.0.jar的jar包,

    然后新建一个CompareNamePinyin类:

package util;

import java.util.Comparator;

import net.sourceforge.pinyin4j.PinyinHelper;
import cn.com.picc.innerControl.commonModle.domain.ComDepartment;

public class CompareNamePinyin implements Comparator<Object>{

 public int compare(Object obj1, Object obj2) {
  ComDepartment dept1 = (ComDepartment)obj1;
  ComDepartment dept2 = (ComDepartment)obj2;
        String o1 = dept1.getDeptName();
        String o2 = dept2.getDeptName();
       
        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];
    }


}

最后调用此方法就行:

//查询出所有总公司下的部门  并按照拼音排序
  tbDepartmentList = comDepartmentService.findSubComDepartmentList("2012062522193606093v1j8","1");
  Collections.sort(tbDepartmentList, new CompareNamePinyin());

你可能感兴趣的:(select 下拉列表内容按拼音排序)