• Post Reply Bookmark Topic Watch Topic
  • New Topic

need help with maps  RSS feed

 
ashish meh
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I have a hashmap and a list:
hashmap1 : [5="five",1="one", 4="four"]
list: "one","four","five"

The list tells the order in which the map should be. So the values in the hashmap match to the collection values. I would like to write a code which will change the order of the hashmap based on the collection. So result should be - hashmap1 : [1="one", 4="four",5="five"]
Can you please help on how to achieve this?
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you need Map to be sorted by key use TreeMap. You can pass your map as a parameter to TreeMap constructor.
If you need Map to remember insertion order use LinkedHashMap.
You can't sort a HashMap. You can get a new sorted map based on the HashMap you have.
 
Campbell Ritchie
Marshal
Posts: 56581
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I recommend the Java Tutorials; you can read about maps in there. Also read the whole of the “trail” if possible.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!