import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
/**
* 中文按笔画排序
* */
public class ChineseNameSort {
public static List<String> sortChineseNames(String lines) throws IOException, URISyntaxException {
// 读取汉字笔画排序字典
Path orderDictPath = Paths.get(ChineseNameSort.class.getClassLoader().getResource("chinese_order_dict.txt").toURI());
// 将名字字符串拆分成列表
List<String> names = new ArrayList<>(Arrays.asList(lines.split("、")));
// 读取汉字笔画排序字典
HashMap<Character, Integer> charOrder = new HashMap<>();
Files.readAllLines(orderDictPath).forEach(line -> {
String[] charOrderArr = line.split("\\s");
charOrder.put(charOrderArr[0].charAt(0), Integer.valueOf(charOrderArr[1]));
});
return names.stream().sorted(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// 注释内容不参与排序
if (o1.contains("(")) {
o1 = o1.substring(0, o1.indexOf("("));
}
if (o2.contains("(")) {
o2 = o2.substring(0, o2.indexOf("("));
}
int len = Math.min(o1.length(), o2.length());
for (int i = 0; i < len; i++) {
int num1 = charOrder.getOrDefault(o1.charAt(i), 0);
int num2 = charOrder.getOrDefault(o2.charAt(i), 0);
if (num1 != num2) {
return num1 - num2;
} else {
// 姓氏相同,名字长度短的在前
if (o1.length() != o2.length()) {
return o1.length() - o2.length();
}
}
}
return 0;
}
}).collect(Collectors.toList()); // 使用 Collectors.toList() 替代 toList()
}
}
直接复制chinese_order_dict.txt连接