简体   繁体   English

树形图如何处理将键放在同一索引上的情况?

[英]How treemap handles case of putting key on same index?

I tried out following code:我尝试了以下代码:

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);
}

But output is coming as:但是 output 是这样的:

{t.i.o=e, ty.r.r.r=c, p.u.r.w.e=d}

Why we are not getting all the five keys in output?为什么我们没有得到 output 中的所有五个键?

EDIT:编辑:

Thank you all, I understood why I'm not getting all 5 keys in output, but I just wondering what would be best way to get all keys in sorted order of dots.谢谢大家,我明白为什么我没有在 output 中获得所有 5 个键,但我只是想知道按点排序顺序获取所有键的最佳方法是什么。

One idea, came to my mind is extract all keys, store them in list and sort that list based on no of dots, then use the same list to reorder the map?我想到的一个想法是提取所有键,将它们存储在列表中并根据点数对该列表进行排序,然后使用相同的列表重新排序 map? Any better ways任何更好的方法

Because numbers of dots in the keys are:因为键中的点数是:

3
2
3
4
2

Unique counts are: 2, 3 and 4唯一计数是: 2, 3 and 4

The put method in TreeMap uses the comparator you specified to check for equality. TreeMap中的put方法使用您指定的比较器来检查是否相等。 If your comparator returns 0 on two keys, it considers them identical.如果您的比较器在两个键上返回0 ,则认为它们相同。

For your data, this means that all Strings with an equal number of dots are considered identical keys.对于您的数据,这意味着具有相同点数的所有字符串都被视为相同的键。

Relevant source: https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/TreeMap.java#L795相关来源: https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/TreeMap.java#L795

.replace(".", "") is strictly superior (replace also replaces all occurrences; it is simply not also using regular expressions. You should fix this part of your code). .replace(".", "")绝对优越(replace替换所有出现的地方;它根本不使用正则表达式。你应该修复这部分代码)。

The easy solution is to have a secondary sorting order.简单的解决方案是进行二级排序。 How should tio and jky sort relatively to each other? tio 和 jky 应该如何相对排序? For example, if you want alphabetical:例如,如果您想要按字母顺序排列:

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));

Note the use of 'thenComparing' to establish a secondary sorting order, to be used when the first would otherwise result in equality.请注意使用“thenComparing”来建立第二个排序顺序,当第一个会导致相等时使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM