tags:

views:

340

answers:

3

What is the easiest way to convert a 2D array of Strings into a HashMap?

For example, take this:

final String[][] sheetMap = { /* XSD Name,  XSL Sheet Name */
                              {"FileHeader", "FileHeader"}, 
                              {"AccountRecord", "AccountRecord"}, 
                              {"DriverCardRecord", "DriverCardRecord"}, 
                              {"AssetCardRecord", "AssetCardRecord"},
                              {"SiteCardRecord", "SiteCardRecord"}
                            };

This is most likely going to be loaded from a file and will be much bigger.

+6  A: 
final Map<String, String> map = new HashMap<String, String>(sheetMap.length);
for (String[] mapping : sheetMap)
{
    map.put(mapping[0], mapping[1]);
}
Andrzej Doyle
+1 ya beat me to it by mere seconds :-)
Jim Garrison
+1: Sometimes the simplest solution =is= the best solution.
DivineWolfwood
+1  A: 

If you just want to initialize your map in a convenient way, you can use double brace initialization:

Map<String, String > sheetMap = new HashMap<String, String >() {{
   put( "FileHeader", "FileHeader" ); 
   put( "AccountRecord", "AccountRecord" ); 
   put( "DriverCardRecord", "DriverCardRecord" ); 
   put( "AssetCardRecord", "AssetCardRecord" );
   put( "SiteCardRecord", "SiteCardRecord" );
}};
tangens
A: 

Wait; if this is going to be loaded from a file, don't go through the intermediate array step! You would have had to load it all first before creating the array or you wouldn't know the size for the array. Just create a HashMap and add each entry as you read it.

Kevin Bourrillion
Yeah, that's the plan. However, I don't know where the information is going to be stored at the moment so I just hard coded it into the array. It did bring up the question of if the Collections framework already contained a utility method to accomplish this task, even though it is trivial to implement. I would rather use a method in the collections wherever possible.
Casey
ah. well, yeah, it doesn't. if it did, it would accept a Collection of something, not an array. Maybe of Map.Entry's. But this is not really very useful. Looping is better.
Kevin Bourrillion