1

I need to sort this TreeMap by values and if value is the same like 1 or 2 in this case then I need to sort these elements by their keys. How can I do it?

{65=2, 67=1, 69=4, 72=2, 73=5, 77=1, 78=2, 79=3, 81=1, 83=7, 84=6, 85=2, 87=2, 89=1}

So the result would looks like this

{83=7, 84=6, 73=5, 69=4, 79=3, 65=2, 72=2, 78=2, 85=2, 87=2, 67=1, 77=1, 81=1, 89=1}

Thank you for help.

  • 1
    By its nature, a Map can't be sorted by its values (as its look mechanism is based on the keys). You could use a List which contains the keys, you could then use a custom Comparator to sort it based on the values associated with the key. You'd then be able to use the List to get the key (in order) and the lookup the value in the Map – MadProgrammer Oct 01 '15 at 21:07

1 Answers1

1

You can't actually sort a TreeMap by its values intuitively. This post on the site explains how to tackle your predicament.

Community
  • 1
  • 1
dxdy
  • 540
  • 2
  • 13
  • *"Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline."* – MadProgrammer Oct 01 '15 at 21:09
  • What about to use HashMap? I am new in Java and I am not sure if program in your post will sort my collection accordig to my imagines. Thank you. – František Pártl Oct 01 '15 at 21:40