
在Java中,`TreeMap`是一个基于红黑树实现的`Map`接口,它能够保持键的有序性。默认情况下,如果`TreeMap`的键是`String`类型,它会按照字符串的自然顺序(即字典序)进行升序排列。这意味着,"10"会排在"2"之前,因为它比较的是字符而不是数值。然而,在某些场景下,我们可能需要根据`String`键所代表的数值大小进行排序,甚至要求是降序排列,例如将"5903766410"排在"5903767"之前。
import java.util.Map;
import java.util.TreeMap;
public class ApplicationMain {
public static void main(String[] args) {
final Map<String, Integer> sampleTreeMap = new TreeMap<>();
sampleTreeMap.put("5903766131", 6);
sampleTreeMap.put("5903767", 7);
sampleTreeMap.put("590376614", 5);
sampleTreeMap.put("5903766170", 9);
sampleTreeMap.put("59037662", 12);
sampleTreeMap.put("5903766410", 10);
System.out.println("默认TreeMap排序结果:");
sampleTreeMap.entrySet().forEach(entry -> {
System.out.println("Key : " + entry.getKey() + " -- " + entry.getValue());
});
}
}其输出将是:
默认TreeMap排序结果: Key : 5903766131 -- 6 Key : 590376614 -- 5 Key : 5903766170 -- 9 Key : 59037662 -- 12 Key : 5903766410 -- 10 Key : 5903767 -- 7
这显然不是按照数值大小或长度降序排列的,因为"5903767"(数值最小,长度最短)却排在最后。
下面是具体的实现代码:
立即学习“Java免费学习笔记(深入)”;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class ApplicationMain {
public static void main(String[] args) {
// 创建一个自定义Comparator,将String键解析为Long并进行降序比较
final Map<String, Integer> sampleTreeMap =
new TreeMap<>(Comparator.comparingLong((String s) -> Long.parseLong(s)).reversed());
sampleTreeMap.put("5903766131", 6);
sampleTreeMap.put("5903767", 7);
sampleTreeMap.put("590376614", 5);
sampleTreeMap.put("5903766170", 9);
sampleTreeMap.put("59037662", 12);
sampleTreeMap.put("5903766410", 10);
System.out.println("\n自定义Comparator排序结果(数值降序):");
sampleTreeMap.entrySet().forEach(entry -> {
System.out.println("Key : " + entry.getKey() + " -- " + entry.getValue());
});
}
}在这个解决方案中:
运行上述代码,将得到期望的输出:
自定义Comparator排序结果(数值降序): Key : 5903766410 -- 10 Key : 5903766170 -- 9 Key : 5903766131 -- 6 Key : 590376614 -- 5 Key : 59037662 -- 12 Key : 5903767 -- 7
现在,键已经按照它们所代表的数值大小进行降序排列,并且原始的String数据类型得到了保留。
通过自定义Comparator,TreeMap能够轻松应对各种复杂的排序需求,即使键的原始类型与期望的排序逻辑不直接匹配。掌握Comparator的使用是有效利用TreeMap的关键。
以上就是Java TreeMap自定义字符串键值排序:实现数字或长度降序排列的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号