2

Below is a piece of code which I use for inserting the values in a hashmap.

String[] folders={"Movies/HD/By Genre/Action","Movies/HD/By Genre/Comedy"};
HashMap<String, String> sdsResults = new HashMap<String, String>();

for(int i=0; i<folders.length; i++){
    sdsResults.put(folders[i], null);
}

Iterator<String> itr = sdsResults.keySet().iterator();
while(itr.hasNext()){
    System.out.println("keys in map are = "+itr.next());
}

The output is -

keys in map are = Movies/HD/By Genre/Comedy
keys in map are = Movies/HD/By Genre/Action

Now I wanted to keys to come in the same order as how I had put in. i.e. first the Action one should come and then the Comedy. But reverse order is coming.

Can someone explain why is it so? And I want the order to be the same as the folder contents. How can I achieve this?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Swati
  • 21
  • 1
  • 4

3 Answers3

1

The order of keys in a hash is not defined. You want a map. Here's a comparison of the internals.

Basically, when you put something in a hash, you scramble the key. This is a one-way function. The whole point is that you can't un-do it -- it's a way of putting 100 things in 10 boxes.

spraff
  • 32,570
  • 22
  • 121
  • 229
  • So is there any other way to get the keys in a specific order.Any other collection type that I can use – Swati Jul 07 '11 at 10:17
  • A map is the correct abstract data type. There may be different implementations (binary trees, skip lists, ... ) – spraff Jul 07 '11 at 15:46
  • Of course you could aleways maintain a separate vector of your keys! – spraff Jul 07 '11 at 15:47
1

LinkedHashMap should solve the problem of ordering. Similar question and the answer here Order of values retrieved from a HashMap

Community
  • 1
  • 1
iCrus
  • 1,210
  • 16
  • 30
-1

You can use ListOrderedMap from Apache's Commons-Collection library to keep the order.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
erich3000
  • 1
  • 1