| Author |
Sort and Print HashMap - Please Help
|
Mulugeta Maru
Ranch Hand
Joined: Jan 20, 2003
Posts: 68
|
|
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
Joined: Dec 10, 2001
Posts: 7023
|
|
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."
|
[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
|
 |
Mulugeta Maru
Ranch Hand
Joined: Jan 20, 2003
Posts: 68
|
|
|
How do you print the TreeMap? Sorry for being dum.
|
 |
Dirk Schreckmann
Sheriff
Joined: Dec 10, 2001
Posts: 7023
|
|
|
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
Joined: Dec 10, 2001
Posts: 7023
|
|
|
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
Joined: Jan 20, 2003
Posts: 68
|
|
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
Joined: Jan 30, 2000
Posts: 18670
|
|
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 ]
|
"I'm not back." - Bill Harding, Twister
|
 |
 |
|
|
subject: Sort and Print HashMap - Please Help
|
|
|