树图如何处理将键放在同一索引上的情况?
How treemap handles case of putting key on same index?
我尝试了以下代码:
public static void main (String[] args) throws java.lang.Exception
{
// sorting based on number of dots
Map<String, String> map =new TreeMap<>((o1, o2) -> {
int noOfDots1 = o1.length() - o1.replaceAll("\.", "").length() ;
int noOfDots2 = o2.length() - o2.replaceAll("\.", "").length() ;
return noOfDots1 - noOfDots2;
});
map.put("ty.r.r.r", "a");
map.put("t.i.o", "b");
map.put("i.o.y.y", "c");
map.put("p.u.r.w.e", "d");
map.put("j.k.i", "e");
System.out.println(map);
}
但输出如下:
{t.i.o=e, ty.r.r.r=c, p.u.r.w.e=d}
为什么我们没有得到输出中的所有五个键?
编辑:
谢谢大家,我明白为什么我没有在输出中得到所有 5 个键,但我只是想知道什么是按点的排序顺序获取所有键的最佳方法。
我想到的一个想法是提取所有键,将它们存储在列表中并根据点数对该列表进行排序,然后使用相同的列表对地图重新排序?还有什么更好的方法
因为按键中的点数是:
3
2
3
4
2
唯一计数为:2, 3 and 4
TreeMap
中的 put
方法使用您指定的比较器来检查相等性。如果您的比较器 returns 0
在两个键上,它认为它们相同。
对于您的数据,这意味着所有具有相同点数的字符串都被视为相同的键。
相关来源:https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/TreeMap.java#L795
.replace(".", "")
绝对优越(替换 也 替换所有出现的地方;它根本不使用正则表达式。您应该修复这部分代码)。
简单的解决方案是采用次要排序顺序。 t.i.o 和 j.k.y 应该如何相互排序?例如,如果您想要按字母顺序排列:
Comparator<String> a = (o1, o2) ->
o1.length() - o1.replace(".", "").length() -
(o2.length() - o2.replace(".", "").length());
Comparator<String> b = Comparator.naturalOrder();
var map = new TreeMap<String, String>(a.thenComparing(b));
请注意使用 'thenComparing' 来建立次要排序顺序,在第一个排序顺序会导致相等时使用。
我尝试了以下代码:
public static void main (String[] args) throws java.lang.Exception
{
// sorting based on number of dots
Map<String, String> map =new TreeMap<>((o1, o2) -> {
int noOfDots1 = o1.length() - o1.replaceAll("\.", "").length() ;
int noOfDots2 = o2.length() - o2.replaceAll("\.", "").length() ;
return noOfDots1 - noOfDots2;
});
map.put("ty.r.r.r", "a");
map.put("t.i.o", "b");
map.put("i.o.y.y", "c");
map.put("p.u.r.w.e", "d");
map.put("j.k.i", "e");
System.out.println(map);
}
但输出如下:
{t.i.o=e, ty.r.r.r=c, p.u.r.w.e=d}
为什么我们没有得到输出中的所有五个键?
编辑:
谢谢大家,我明白为什么我没有在输出中得到所有 5 个键,但我只是想知道什么是按点的排序顺序获取所有键的最佳方法。
我想到的一个想法是提取所有键,将它们存储在列表中并根据点数对该列表进行排序,然后使用相同的列表对地图重新排序?还有什么更好的方法
因为按键中的点数是:
3
2
3
4
2
唯一计数为:2, 3 and 4
TreeMap
中的 put
方法使用您指定的比较器来检查相等性。如果您的比较器 returns 0
在两个键上,它认为它们相同。
对于您的数据,这意味着所有具有相同点数的字符串都被视为相同的键。
相关来源:https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/TreeMap.java#L795
.replace(".", "")
绝对优越(替换 也 替换所有出现的地方;它根本不使用正则表达式。您应该修复这部分代码)。
简单的解决方案是采用次要排序顺序。 t.i.o 和 j.k.y 应该如何相互排序?例如,如果您想要按字母顺序排列:
Comparator<String> a = (o1, o2) ->
o1.length() - o1.replace(".", "").length() -
(o2.length() - o2.replace(".", "").length());
Comparator<String> b = Comparator.naturalOrder();
var map = new TreeMap<String, String>(a.thenComparing(b));
请注意使用 'thenComparing' 来建立次要排序顺序,在第一个排序顺序会导致相等时使用。