Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to change the order of a Linked hashMap  RSS feed

 
yuga dev
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
yuga dev
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yuga,

Can you please help us by telling how would you get the keys in real scenario.

Regards,
Patricia
 
yuga dev
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!