5.21. Retrieving Map Values Without Casting
Problem
You need to retrieve a primitive
double from a Map, but the
value is stored as a Double object.
Solution
Use MapUtils.getDoubleValue()
to retrieve a Double
object from a Map as a double
primitive. The following example demonstrates
getDoubleValue( ):
import java.util.*;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.collections.MapUtils;
Object[] mapArray = new Object[][] {
{ "A", new Double( 2.0 ) },
{ "B", new Double( 0.223242 ) },
{ "C", new Double( 2828e4 ) },
{ "D", "GARBAGE"} };
Map numberMap = ArrayUtils.toMap( mapArray );
double a = MapUtils.getDoubleValue( numberMap, "A" );
double b = MapUtils.getDoubleValue( numberMap, "B" );
double c = MapUtils.getDoubleValue( numberMap, "C" );
double d = MapUtils.getDoubleValue( numberMap, "D", new Double( Double.NaN ) );
System.out.println( "A = " + a );
System.out.println( "B = " + b );
System.out.println( "C = " + c );
System.out.println( "D = " + d );This simple utility retrieves four doubles from
numberMap; the fourth call to
getDoubleValue( ) supplies a default
double to be returned if the
value’s type cannot be converted to a
double. This example produces the following
output:
A = 2.0 B = 0.223242 C = 28280.0 D = NaN
Discussion
This utility is laughably simple, but if you are working with
numbers, this utility can help you avoid casting and calling
doubleValue( ). In addition to
MapUtils.getDoubleValue( ),
MapUtils also contains the
MapUtils.getDouble( ) ...
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