Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sort and Print HashMap - Please Help

 
Mulugeta Maru
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a way to sort a HashMap and print the list. The HashMap contains key = name and Value = phone number. I would like to sort it by name and print the list.
Please help.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use keySet() to get a Set view of the keys contained in the Map. Then you could sort the Set and iterator through it, getting the values from the Map.
Or, perhaps more simply, make a TreeMap using your existing Map. A TreeMap "guarantees that the map will be in ascending key order."
 
Mulugeta Maru
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you print the TreeMap? Sorry for being dum.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That sort of depends on how you want to print the TreeMap. How do you want to print it? What have you tried so far? Post example code showing what you've worked on (and don't forget to surround the code with the [code] and [/code] UBB tags).
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that a TreeMap has a toSring method (inherited from AbstractMap) that might format the output as you'd like it formatted.
 
Mulugeta Maru
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your help. Yes the toString method is very helpful to format the print out. The TreeMap also keeps the sort order which is very good.
Thanks again.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general, if you want to print the TreeMap entries in order, using any format other than the one supplied by toString(), you should use the entrySet() method and iterate through the entries:

[ April 08, 2003: Message edited by: Jim Yingst ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic