1

Let's say I have a hashmap as below

Map<String,List<String>> nameMap = new HashMap<String,List<String>>();

Also I already have the following key values in the hashmap

Martin - 1 Julia - 3 Andrew - 2 Steve - 5

Now The question is I have a particular order which I need the hashmap to hold and when I print out the entries in the map it should print in the order I need.

The order I need is

Julia - 3 Andrew - 2 Steve - 5 Martin - 1

I know I can use linked hashmap to preserve the order. but my original one is a Hashmap and how do I arrange it in the order I need?

Damien-Amen
  • 7,232
  • 12
  • 46
  • 75
  • 2
    In what is your criteria to order based, if you don't explain, it just looks random to me. – Marcelo Oct 25 '13 at 14:54
  • 1
    http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html "This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time." In short, you don't want to just rely on hashmap alone to get you a certain order. You're going to need to bring some other things into play. – Joe Oct 25 '13 at 14:55
  • You can't order a HashMap - the entries are arranged according to the hash value of the key. – Paul Oct 25 '13 at 14:56
  • http://stackoverflow.com/questions/780541/how-to-sort-hash-map – kosa Oct 25 '13 at 14:56
  • If there exist a fixed criteria that you can apply for sorting you can use Collections.sort(list, comparator); to sort the elements in the order you want. list is your list that you want to sort and comparator is a class that implements Comparator interface. – Luke Oct 25 '13 at 14:56
  • @Marcelo : there is no criteria. I just need it in the order that I just mentioned. I don't mind if it can be hardcoded or something like that – Damien-Amen Oct 25 '13 at 14:57
  • The answer to questions like this is always "HashMap order is random; use LinkedHashMap". Since you already know both those facts, I don't know what more you want. – Boann Oct 25 '13 at 15:01

3 Answers3

3

Since HashMap is unsorted, and because it cannot be sorted in place due to the way that it is constructed *, you have two simple options here:

  • Create a LinkedHashMap, and populate it with the data from your original HashMap in the desired order, or
  • Cereate a temporary list from the keySet of your HashMap, order it as desired, and then iterate that sorted set, and retrieve the data from the original HashMap in the desired order.
    * HashMap entries are arranged in "buckets" according to their hash code, which is very much arbitrary.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

HashMap is unordered. You can use LinkedHashMap

PSR
  • 39,804
  • 41
  • 111
  • 151
0

HashMap is unordered colection(the items are ordered by the hash and you can't rely on that). You can use TreeMap.

Evgeni Dimitrov
  • 21,976
  • 33
  • 120
  • 145