OptionalDouble, a sister to OptionalLong and OptionalInt , is a new class introduced in Java 8 which is a container object that may or may not contain a double value. If a double is present, isPresent() will return true and getAsDouble() will return the value.
When dealing with non primitive values, see java.util.Optional example .
getAsDouble @Test
public void optional_double_getAsDouble () {
OptionalDouble optionalDouble = OptionalDouble . of ( 90 );
assertEquals ( 90 , optionalDouble . getAsDouble (), 0 );
}
ifPresent @Test
public void optional_double_ifPresent () {
OptionalDouble optionalDouble = OptionalDouble . of ( 56 );
optionalDouble . ifPresent ( p -> System . out . println ( p ));
// or
optionalDouble . ifPresent ( System . out :: println );
}
isPresent @Test
public void optional_double_isPresent () {
OptionalDouble optionalDouble = OptionalDouble . of ( 56 );
assertTrue ( optionalDouble . isPresent ());
}
orElse @Test
public void optional_double_orElse () {
OptionalDouble optionalDouble = OptionalDouble . empty ();
assertEquals ( 77 , optionalDouble . orElse ( 77 ), 0 );
}
orElseGet @Test
public void optional_double_orElseGet () {
OptionalDouble optionalDouble = OptionalDouble . empty ();
assertEquals ( 10 , optionalDouble . orElseGet (() -> 10 ), 0 );
// or
DoubleSupplier doubleSupplier = new DoubleSupplier () {
@Override
public double getAsDouble () {
return 10 ;
}
};
assertEquals ( 10 , optionalDouble . orElseGet ( doubleSupplier ), 0 );
}
orElseThrow @Test ( expected = IllegalStateException . class )
public void optional_double_orElseThrow () {
OptionalDouble optionalFramework = OptionalDouble . empty ();
optionalFramework . orElseThrow ( IllegalStateException: : new );
}
empty @Test
public void optional_double_empty () {
OptionalDouble optionalDouble = OptionalDouble . empty ();
assertFalse ( optionalDouble . isPresent ());
}
of @Test
public void optional_double_of () {
OptionalDouble optionalDouble = OptionalDouble . of ( 89 );
assertEquals ( 89 , optionalDouble . getAsDouble (), 0 );
}
OptionalDouble Example posted by Justin Musgrove on 23 February 2014
Tagged: java and java-util
Share on: Facebook Google+
All the code on this page is available on github:
OptionalDoubleExample.java