aspose file tools
The moose likes Java in General and the fly likes Map Issues Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Map Issues" Watch "Map Issues" New topic
Author

Map Issues

rahul karwal
Ranch Hand

Joined: Oct 26, 2001
Posts: 73
Hi,
I am using a Hash Map, and i add following values : -

Map map = new HashMap();

map.put("Any","-1");
map.put("Below $100","101");
map.put("$100 - 199","100");
map.put("200 - 299","-200");

when i get the output i get in different order then the order i inserted, any idea how to get teh output in the same order as the insertion.
I also tried to use "LinkedHashMap" i get the same output.
Thanks
aziz
Julian Kennedy
Ranch Hand

Joined: Aug 02, 2004
Posts: 823
Well, a TreeMap is a SortedMap but you'd have to provide your own Comparator to determine the order. That can be a bit tricky and doesn't feel appropriate given your data.

The first thing that sprang to mind is to use a List of Map.Entry. However, that has a strong smell of hack about it and you would only be able to access the entries using the List methods, not the Map methods, i.e. no automatic get value by key look-up.

After a little more thought I think the best solution is to use the OrderedMap implementation (LinkedMap) from Jakarta Commons Collections.

Jules
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
I am more than a bit mystified by
Originally posted by Aziz Dhanani:
I also tried to use "LinkedHashMap" i get the same output.
Are you sure you did that right, Aziz? My suggestion would be to use LinkedHashMap, because it guarantees to preserve insertion order when iterating through the map. It works for me and I wonder why it didn't seem to work for you.

I wouldn't use OrderedMap if a JDK class will do just as well.

- Peter
[ September 08, 2004: Message edited by: Peter den Haan ]
Julian Kennedy
Ranch Hand

Joined: Aug 02, 2004
Posts: 823
Having read a little further - ahem - if you instantiate a LinkedHashMap thus:

you get the elements returned in access order rather than insertion order. I imagine it's unlikely you're actually doing that. How are you iterating over the Map to determine the order?

Jules
 
I agree. Here's the link: jrebel
 
subject: Map Issues
 
Similar Threads
Clarification regarding HashMap
HELP - Stuck on a TreeMap key problem
observations in case of Map
Retrieving insertion order of a map
Alternate way of inserting the values in map?