GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes From Array of Objects to HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "From Array of Objects to HashMap" Watch "From Array of Objects to HashMap" New topic
Author

From Array of Objects to HashMap

Patrice Ricard
Greenhorn

Joined: Aug 18, 2005
Posts: 4
Hi everyone
I have an Array of Objects of type Result. One of the property of this Object is dictionary.
I want to create a HashMap which keys are the different dictionaries and values are Array of Result that have the same dictionary property.

hope to be clear.

thanks
Santhosh Kumar
Ranch Hand

Joined: Nov 07, 2000
Posts: 242
Sample code could look like,

Patrice Ricard
Greenhorn

Joined: Aug 18, 2005
Posts: 4
fast reply but that doesn't work
You put a Result Object in the values and not an Array of Result.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

Use a MultiHashMap from Apache Commons. Or something similar.

The idea:
1) Map will be Map<Disctionary, List<Results>>.
2) When you get a Dictionary use map.get(dictionary)
3a) If the result is null, make a new List<Results>
3b) Add the current Results object to the List
3c) Put the List back in the Map keyed to the Dictionary

The MultiMap does this for you.


Steve
Santhosh Kumar
Ranch Hand

Joined: Nov 07, 2000
Posts: 242
Sorry, should have read the question clearly. Modified code may look like,



And convert the List<Result> to Result[] whenever you want to use the array object. Or if you want to do then itself, loop through the Map, read each list and convert to array object.

As Steve mentioned, MultiHashMap does the same thing.
[ August 19, 2008: Message edited by: Santhosh Kumar ]
Patrice Ricard
Greenhorn

Joined: Aug 18, 2005
Posts: 4
thanks to both of you and for your quickness.

I was stuck with Array in my mind and didn't think about List.toArray().
[ August 19, 2008: Message edited by: Patrice Ricard ]
 
GeeCON Prague 2014
 
subject: From Array of Objects to HashMap