Java 列表元素自定义排序
在 Java 开发过程中,有时会遇到需要对列表中元素进行自定义的排序。
这样的排序往往不能由元素本身的特性(比如字符串长度、首字母顺序)判断,需要自己指定顺序。
比如对汉字的数字进行排序,他们的字符串长度都为 1,首字母顺序也不能得到预期的结果,因此需要自定义排序。
以下是示例代码:
public static void main(String[] args) {
// 自定义顺序列表
List<String> customSortList = new ArrayList<>();
customSortList.add("一");
customSortList.add("二");
customSortList.add("三");
customSortList.add("四");
customSortList.add("五");
customSortList.add("六");
customSortList.add("七");
customSortList.add("八");
customSortList.add("九");
// 实际数据列表
List<String> realDataList = new ArrayList<>();
realDataList.add("三");
realDataList.add("九");
realDataList.add("八");
realDataList.add("四");
realDataList.add("五");
realDataList.add("二");
realDataList.add("一");
realDataList.add("六");
realDataList.add("七");
// 自定义排序
realDataList.sort((s1, s2) -> {
// 获取s1在自定义顺序列表中的位置
int index1 = customSortList.indexOf(s1);
// 获取s2在自定义顺序列表中的位置
int index2 = customSortList.indexOf(s2);
// 如果字符串不在自定义顺序列表中,可以决定它们的位置
// 这里假设不在列表中的字符串应该排在最后
if (index1 == -1) {
// 如果两个都不在列表中,则它们相等;否则,s1排在s2后面
return (index2 == -1) ? 0 : 1;
}
// s2不在列表中,所以s1排在s2前面
if (index2 == -1) {
return -1;
}
// 否则,按照自定义顺序列表中的索引进行排序
return Integer.compare(index1, index2);
});
System.out.println(Arrays.toString(realDataList.toArray()));
}
打印结果:
[一, 二, 三, 四, 五, 六, 七, 八, 九]
这样就得到了预期的结果。
如果需要改变排序规则(比如倒序),只需要改变自定义顺序列表的元素添加顺序即可。
天河有尽身作涯,星海无边前是岸。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)