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

Adding key/value pairs from a HashMap in to an ArrayList

 
bob fissle
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to create a HashMap, loop through that HashMap, and finally, I'm trying create an ArrayList of key/value pairs -- from the HashMap -- that contain within its value set a parameter value. I realize that might be a little hard to understand, so I've provided my code to make sense of what I'm trying to accomplish.



For the desired output we can assume that the productAttribute parameter value is "Computer".

Current output of the addProduct ArrayList:


Desired output of the addProduct ArrayList:


I can't seem to figure out what I'm doing wrong. Any help would be greatly appreciated.
 
Paul Clapham
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So you have a map which maps a String to a list of Strings. And if I understand your example right, you want to mutate that into a list of lists of Strings, where each of the inner lists comprises a key of the map followed by the list it's mapped to?

Well, looking at the lists of Strings you have in your example, I don't understand why they are lists of Strings. To me they ought to be some kind of objects which are designed specifically for these products, because obviously the first entry in the list is some kind of a category, the second entry is a manufacturer, and so on. Just putting those things in a list is a misuse of lists.

And likewise I don't see the point of making a slightly different list which just has the product code on the front. Perhaps it should be part of the product object which I was just suggesting. Making a list of products would make a lot of sense once you've done that, which is basically your non-OO requirement anyway.
 
bob fissle
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply Paul. Yes, your understanding of what I'm trying to do is correct. Is there any chance you could provide some pseudo code on a better way of accomplishing the task at hand?
 
Tim Moores
Bartender
Posts: 2895
46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This might be the beginnings of such a class. For the string types, other custom-made classes may be more appropriate; that depends on the design of your app and your requirements.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic