my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Sorting a HasMap by Values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Sorting a HasMap by Values" Watch "Sorting a HasMap by Values" New topic
Author

Sorting a HasMap by Values

Abhik Ghosh
Ranch Hand

Joined: Feb 28, 2008
Posts: 32
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

Joined: Aug 03, 2008
Posts: 9293
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Abhik Ghosh
Ranch Hand

Joined: Feb 28, 2008
Posts: 32
Thanks Ankit. That was a great help..
S Ali
Ranch Hand

Joined: Aug 23, 2009
Posts: 129


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

SCJP 6
Abhik Ghosh
Ranch Hand

Joined: Feb 28, 2008
Posts: 32
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

Joined: Feb 28, 2008
Posts: 32
And Ali.. thanks a lot for correcting my code.
S Ali
Ranch Hand

Joined: Aug 23, 2009
Posts: 129
No problem bro
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6661
    
    5

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.


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
 
Consider Paul's rocket mass heater.
 
subject: Sorting a HasMap by Values