• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Jeanne Boyarsky
  • Tim Cooke
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
Bartenders:

Sorting a Map based on Values

 
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have a Map of Language Code (as Key) and Lanuage (as Value). I have to sort the map based on the values in the map.

But, in addition, there is a requirement that certain languages such as EN=>English, SP=>Spanish will always be on the top of the map. So, please suggest a suitable approach to achieve this.

Thanks.
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First of all you have to be using a Map implementation that supports sorting (suitable Maps will be those that implement the SortedMap interface) and then you need to write a suitable Comparator, an instance of which you pass to your Map's constructor.
Remember that the Comparator operates on the Keys in the Map, so you will have to fetch the appropriate Values when implementing the compare method.
 
Marshal
Posts: 78671
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You also need to apply criteria to the keys for them to be sorted with.
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Vaibhav G Garg wrote:I have a Map of Language Code (as Key) and Lanuage (as Value). I have to sort the map based on the values in the map.


This might sound a bit nitpicky, but you don't sort a Map; it has an intrinsic order, which is quite different.

Sorting is an action. I can take a "random" List of items and sort it any way I like, but a Map's order is determined at the time it's created and cannot be changed after that.

So what you actually want to know is how to order a Map the way you want and, as Joanne said, a custom Comparator (java.util.Comparator) sounds like what you want.

HIH

Winston
 
Doe, a deer, a female deer. Ray, a pockeful of sun. Me, a name, I call my tiny ad ...
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic