How treemap handles case of putting key on same index?

Tags: , , ,

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

But output is coming as :

{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?


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.

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? Any better ways


Because numbers of dots in the keys are :


Unique counts are : 2, 3 and 4

Source: stackoverflow