We help IT Professionals succeed at work.

Java Hashmap Sorting

lcor
lcor asked
on
9,771 Views
Last Modified: 2013-11-24
I have a sorting issue with a Hashmap.  My constraint is that I MUST use the Hashmap and work with existing code.  I do a database query and place the results in a Hashmap.  When I iterate thru the Hashmap, it loses the original alphabetical sorting done by the database.  So, my problem is that I must sort the results coming out of the Hashmap which is then placed into another class.

Here's the code:

Hashmap hm = (database results)
Iterator it =  hm.keySet().iterator();

while (it.hasNext()) {
    String key = (String) it.next();
    STring value = (String) hm.get(key);
                                                                    <<<------------------I must do alphabetical sorting before
                                                                    <<<-----------------placing results (value) into this other class
    some_other_class.addVAlue(new Integer(value), "title");
}
 
There isn't a great number of values (most a couple hundred) so if another loop is okay.
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016

Commented:
HashMap has no order. Use LinkedHashMap to preserve order
CERTIFIED EXPERT
Top Expert 2016

Commented:
(So if you preserve the order, you won't need to sort it again)
Java Architect
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
CERTIFIED EXPERT
Top Expert 2016

Commented:
Well of course you don't need to take the performance hit of sorting at all, other than at the db. Just put them in to the LinkedHashMap as they come out of the ResultSet
Bart CremersJava Architect

Commented:
I'd go with CEHJ's solution if you can alter the outcome from the database to a LinkedHashMap. If not you'll need to go with the sorting.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
use the follwoiwing:

List list = new ArrayList(hm.values());
Arrays.sort(list);
while (it.hasNext()) {
    String value = (String) it.next();
    some_other_class.addVAlue(new Integer(value), "title");
}

Author

Commented:
Everyone had great input but I ended up using Bart_Cr's solution in the end.
CERTIFIED EXPERT
Top Expert 2016

Commented:
What made you want to sort them twice?
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.