导入依赖: 查询首字母的读音
获取首字母工具类,对于多音字只取第一个读音
import net.sourceforge.pinyin4j.PinyinHelper;import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;import java.util.regex.Matcher;import java.util.regex.Pattern;public class ChineseCharacterUtil { public static String getUpperCase(String chinese, boolean isFull) { return convertHanzi2Pinyin(chinese, isFull).toUpperCase(); } public static String getLowerCase(String chinese, boolean isFull) { return convertHanzi2Pinyin(chinese, isFull).toLowerCase(); } private static String convertHanzi2Pinyin(String hanzi, boolean isFull) { String regExp = "^[u4E00-u9FFF]+$"; StringBuffer sb = new StringBuffer(); if (hanzi == null || "".equals(hanzi.trim())) { return ""; } String pinyin = ""; for (int i = 0; i < hanzi.length(); i++) { char unit = hanzi.charAt(i); //是汉字,则转拼音 if (match(String.valueOf(unit), regExp)) { pinyin = convertSingleHanzi2Pinyin(unit); if (isFull) { sb.append(pinyin); } else { sb.append(pinyin.charAt(0)); } } else { sb.append(unit); } } return sb.toString(); } private static String convertSingleHanzi2Pinyin(char hanzi) { HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat(); outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); String[] res; StringBuffer sb = new StringBuffer(); try { res = PinyinHelper.toHanyuPinyinStringArray(hanzi, outputFormat); sb.append(res[0]);//对于多音字,只用第一个拼音 } catch (Exception e) { e.printStackTrace(); return ""; } return sb.toString(); } private static boolean match(String str, String regex) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); return matcher.find(); }}
首字母和首字母对应的数据集合对象:
import lombok.Data;import java.util.ArrayList;import java.util.List;@Datapublic class AreaLetter implements Comparable{ private String letter; private List
//代码逻辑实现
public List getAreaLetter() { // 从数据库查询的姓名或者地址集合 List
第一次写,是个菜鸟,有问题 希望大家指出来,谢谢大家