JAVA 实现 名单按姓氏笔画为序排列

该博客介绍了如何使用Java实现一个按汉字姓氏笔画排序的程序。作者首先读取汉字笔画排序字典,然后对指定名单进行处理,忽略特定注释内容,并通过自定义比较器进行排序。最后,程序打印出按姓氏笔画升序排列的名单。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;


/**
 * JAVA 实现 名单按姓氏笔画为序排列。
 * @author Kwok
 * 2022-10-24
 */
public class ChineseNameSort {

	public static void main(String[] args) throws Exception {
		
		// 读取汉字笔画排序字典
		HashMap<Character, Integer> char_order = new HashMap<Character, Integer>();
		Path chinese_order_dict = Paths.get(ChineseNameSort.class.getResource("chinese_order_dict.txt").toURI());
		
		Files.readAllLines(chinese_order_dict).forEach(line -> {
			String[] char_order_arr = line.split("\\s");
			char_order.put(char_order_arr[0].charAt(0), Integer.valueOf(char_order_arr[1]));
		});
		// System.out.println(char_order);
		
		
		// 以昨日公布名单为例
		Path test_path = Paths.get("D:\\opt\\20th-first.txt");
		List<String> lines = Files.readAllLines(test_path);
		
		lines.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("("));
				}
				/* 注释内容不参与排序 END */
				
				
				int len = o1.length() < o2.length() ? o1.length() : o2.length();
				for (int i = 0; i < len; i++) {
					int num1 = char_order.getOrDefault(o1.charAt(i), 0);
					int num2 = char_order.getOrDefault(o2.charAt(i), 0);
					if (num1 != num2) {
						return num1 - num2;
					}else{
						// 姓氏相同,名字长度短的在前
						if(o1.length()!= o2.length()) {
							return o1.length() - o2.length();
						}
					}
				}
				return 0;
			}
		}).forEach(System.out::println);

	}
	
}

注:`chinese_order_dict.txt` 资源地址:https://download.csdn.net/download/guokexiaohao/86815163

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值