This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting a HasMap by Values

 
Abhik Ghosh
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to sort a HasMap by its values.

My code is :


But it is giving output as :
Name@3e0e7bf=Val@923e30
Name@4711993=Val@130c19b
Name@3c78865=Val@1f6a7b9

I want it to be sorted by the values.

Please help.
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HashMap is not an ordered collection, you'll have to use an ordered collection like LinkedHashMap to be able to sort it. I'm quite sure there's nothing in the java API to sort it, you'll have to sort it manually, google is filled with solution for this - Link1, link2, link3, link4...
 
Abhik Ghosh
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ankit. That was a great help..
 
S Ali
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


1- first you defined your Treemap but you didn't put entries of Hashmap in it.
s.putAll(m);

2- second in your comparator you should have compared the map's values getting them thought your key so it can iterate on all values of the map.

The code now prints:
Charu=68
Mohan=89
Angit=10
{Angit=10, Charu=68, Mohan=89} -----> after sorting
 
Abhik Ghosh
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ali. I have also just written a fresh code that sorts a HashMap both by keys as well as by values.
Here it is:
 
Abhik Ghosh
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And Ali.. thanks a lot for correcting my code.
 
S Ali
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No problem bro
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To add to your discussion, it is very unlikely that a hashmap would need to be sorted by its values. If there is a requirement that dictates that this should happen, you should look at your problem and data structure selection again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic