1.12. Creating a Map from a Multidimensional Array
Problem
You need to create a Map from
a
multidimensional array.
Solution
Use ArrayUtils.toMap()
to create a Map from a
two-dimensional array (Object[][]). Example 1-8 demonstrates the creation of such a
Map. Example 1-8 takes an
Object[][] representing atomic symbols and atomic
weights and turns it into a Map retrieving the
atomic weight for hydrogen.
Example 1-8. Creating a Map from an Object[ ][ ]
import org.apache.commons.lang.ArrayUtils;
Object[] weightArray =
new Object[][] { {"H" , new Double( 1.007)},
{"He", new Double( 4.002)},
{"Li", new Double( 6.941)},
{"Be", new Double( 9.012)},
{"B", new Double(10.811)},
{"C", new Double(12.010)},
{"N", new Double(14.007)},
{"O", new Double(15.999)},
{"F", new Double(18.998)},
{"Ne", new Double(20.180)} };
// Create a Map mapping colors.
Map weights = ArrayUtils.toMap( weightArray );
Double hydrogenWeight = map.get( "H" );Discussion
Instead of calling weights.put( ) for each entry
in the Map, an Object[][] is
created and then passed to ArrayUtils.toMap()
. The toMap()
method then extracts the first item in each
array as the key and the second item as the value. This is a simple
way to quickly create a Map in a piece of code;
the alternative to using ArrayUtils.toMap( ) is to
simply create a Map and repeatedly call the
put( ) method.
See Also
In the previous example, Double objects are added
to a Map, and values are retrieved from the
Map using get( ). Commons Collections contains utility ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access