Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

List in HashMap

 
AbhiRam Kalyan
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
I want to iterate through the list in HashMap and store the values as key and keys as values in a new hashmap.

Here is the HashMap with array list:
{secondval=[A3], firstval=[A2, A1], thirdval=[A4]}
Now i would like to store this in a new hashmap as {A1=firstval,A2=firstval,A3=thirdval,A4=fourthval}..

Please tell me what is the efficient way to iterate and store values in a new Hashmap.
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out TreeMap and its constructors.
 
AbhiRam Kalyan
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
didnt get.could you show me an example?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49789
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What didn't you understand about Maps or their implementations, particularly HashMap and TreeMap and how they sort or order their entries?
 
AbhiRam Kalyan
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand about sort order and treemap. What i am trying to do is to create a new hashmap from
{secondval=[A3], firstval=[A2, A1], thirdval=[A4]}
which should represent as
Key Value
A1 firstval
A2 firstval
A3 secondval
A4 thirdval
 
Campbell Ritchie
Sheriff
Pie
Posts: 49789
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So each entry consists of a "V" for value and an array of "K" for keys which it should be applied to. And you want it to order with the "K"s sorted. I would repeat what Rob said: look at TreeMap and read its constructors; there are four overloaded constructors to read about. I presume you have some sort of Comparator already, or A1 and A2 implement Comparable.
 
AbhiRam Kalyan
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for all your support.. i got the solution.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49789
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done Please tell us what the solution was, so anybody having the same problem in the future can search for it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic