最近在做一个类似于微信用户通讯录的功能,所以考虑通过查找的好友列表,在后台遍历按照26个字母分组,前台获取到Json循环26个字母直接解析对应的字符下的名称为一组分隔,没有则不显示,工具如下↓
package ev.viewworld.util;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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 changeChinesePinyinUtil {
/**
* 获取姓名全拼和首字母
* @author 于公成
* @param chinese 汉语名称
* @return fullPinyin : 全拼 simplePinyin : 首字母 groudPinyin:微信用户组第一个字母
* @throws BadHanyuPinyinOutputFormatCombination
*/
public static Map changeChinesePinyin(String chinese) throws BadHanyuPinyinOutputFormatCombination {
Map pinyin = new HashMap();
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
StringBuffer fullPinyin = new StringBuffer();
StringBuffer simplePinyin = new StringBuffer();
StringBuffer firstPinyin = new StringBuffer();
char[] chineseChar = chinese.toCharArray();
for (int i = 0; i < chineseChar.length; i++) {
String[] str = null;
try {
str = PinyinHelper.toHanyuPinyinStringArray(chineseChar[i],
format);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
if (str != null) {
fullPinyin = fullPinyin.append(str[0].toString());
simplePinyin = simplePinyin.append(str[0].charAt(0));
}
if (str == null) {
String regex = "^[0-9]*[a-zA-Z]*+$";
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(String.valueOf(chineseChar[i]));
if (m.find()) {
fullPinyin = fullPinyin.append(chineseChar[i]);
simplePinyin = simplePinyin.append(chineseChar[i]);
}
}
}
String[] name = PinyinHelper.toHanyuPinyinStringArray(chineseChar[0],format);
firstPinyin=firstPinyin.append(name[0].charAt(0));
pinyin.put("fullPinyin", fullPinyin.toString());
pinyin.put("simplePinyin", simplePinyin.toString().toUpperCase());
pinyin.put("groudPinyin", firstPinyin.toString().toUpperCase());
return pinyin;
}
/**
* 按用户拼音首字母分组
* @param list
* @return
* @throws BadHanyuPinyinOutputFormatCombination
*/
public static Map getUserCodeGroup(List list) throws BadHanyuPinyinOutputFormatCombination {
Comparator