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 :
{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?
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.
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
Advertisement
Answer
Because numbers of dots in the keys are :
3 2 3 4 2
Unique counts are : 2, 3 and 4