| Author |
how to change the order of a Linked hashMap
|
yuga dev
Greenhorn
Joined: Nov 02, 2007
Posts: 5
|
|
Hi,
I am having a linked Hashmap which has few entries. I would like add an entry, which has to be added in the first of all the entries.
LinkedHashMap lHashMap = new LinkedHashMap();
lHashMap.put("1","One");
lHashMap.put("2","Two");
lHashMap.put("3","Three");
In the above mentioned code , if i add, lHashMap.put("0","zero");
I would like to be added as ,
lHashMap.put("0","zero");
lHashMap.put("1","One");
lHashMap.put("2","Two");
lHashMap.put("3","Three");
Please help,
Thanks in advance,
Yuga
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
Seems like a TreeMap<Integer,String> is more useful for you. That does require you to omit the quotes around the keys (so 0 instead of "0" - the key will be autoboxed into an Integer) but the TreeMap will keep the keys sorted.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
yuga dev
Greenhorn
Joined: Nov 02, 2007
Posts: 5
|
|
Hi,
Thanks for the reply. But i need to get this value using linked hashmap only. Is it possible to use any logic to derive this?
Thanks,
Yuga.
|
 |
Patricia Samuel
Ranch Hand
Joined: Sep 12, 2007
Posts: 300
|
|
Yuga,
Can you please help us by telling how would you get the keys in real scenario.
Regards,
Patricia
|
 |
yuga dev
Greenhorn
Joined: Nov 02, 2007
Posts: 5
|
|
Patricia,
I am not sure whether you are asking this :
Set st = lHashMap.keySet();
Iterator itr = st.iterator();
while(itr.hasNext())
System.out.println(itr.next());
This is how we generally get list of keys in a hashmap.
Regards,
Yuga
|
 |
Patricia Samuel
Ranch Hand
Joined: Sep 12, 2007
Posts: 300
|
|
|
Noooo, I am asing how would your lHashMap object going to have the keys....I am sure it wont be hard coded like this in real scenario.
|
 |
 |
|
|
subject: how to change the order of a Linked hashMap
|
|
|