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 methods for retrieving Double objects as double primitives; MapUtils.getDouble( ) retrieves an object from a Map, casts it to a Number, and calls doubleValue( ) using the default value supplied if there is no corresponding key in the Map. See Recipe 5.21 for more information about MapUtils.getDouble( ).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.99