jar 包
<!--汉字转拼音-->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
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.exception.BadHanyuPinyinOutputFormatCombination;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* 26字母排序
* 1、将数据list 进行排序Collections,排序后是按照汉字字母排序的
* 2、循环找出26个字母,以字母为key,以list中相同首字母的数据为值(集合)
* 3、需要用到 pinyin4j-2.5.0.jar 这个汉字转拼音的jar包
*/
public class AlphabeticalUtils {
/**
* 获取汉字串拼音,英文字符不变
*/
public static String getFullSpell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 128) {
try {
pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pybf.append(arr[i]);
}
}
return pybf.toString();
}
/**
* 将集合数据按照汉字首字母分组排序
*/
public static Map<String, Object> screenManufacturer(List<String> list) {
try {
Collator com = Collator.getInstance(java.util.Locale.CHINA);
// 按字母排序
Collections.sort(list, com);
// 输出26个字母
Map<String, Object> map = new TreeMap<>();
for (int i = 1; i < 27; i++) {
String word = String.valueOf((char)(96 + i)).toUpperCase();
// 循环找出 首字母一样的数据
List<String> letter = new ArrayList<>();
for (String str : list) {
String pybf = getFullSpell(str);
String zm = pybf.substring(0, 1);
if (word.equals(zm)) {
letter.add(str);
}
}
map.put(word, letter);
}
return map;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args){
ArrayList<String> list = new ArrayList<>();
list.add("张三");
list.add("李四");
list.add("王五");
list.add("王五");
list.add("B王五");
list.add("A王五");
list.add("三");
list.add("阿拉伯");
Map<String, Object> map = screenManufacturer(list);
System.out.print(map);
}
}