Monday, September 4, 2017

Java 8 - Replace null with Optional


NullPointerException is a common exception you may encounter in coding , in Java 8 , you can replace null with optional , thus the NullPointerException can be totally removed. Of course you can also use if statement to judget whether it is null.



public class Car {
 private String name; // A car must have a name
 private Optional<Insurance> insurance; // A can can have insurance or not insured
 
}

Create a Optional


Optional<Car> optCar = Optional.empty(); // a empty Optional
Optional<Car> optCar2 = Optional.of(car); // create an optional from another object
Optional<Car> optCar3 = Optional.ofNullable(car); // A optional can accept null.

Optional<Insurance> optInsurance = Optional.ofNullable(insurance);
Optional<String> name = optInsurance.map(Insurance::getName); // retrive value from Optional Object


// combine multiple filter to retrive
public String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(Person::getCar)
             .flatMap(Car::getInsurance)
             .map(Insurance::getName)
             .orElse("Unknown");
}


// 2 optional judgetments
public Optional<Insurance> FindCheapInsurance(Optional<Person> person, Optional<Car> car {   
 if (person.isPresent() && car.isPresent()) {
  return Optional.of(findCheapestInsurance(person.get(), car.get()));
 } else {
  return Optional.empty();
 }
}

How to use

for example you have a object which is probably containing null.


Object value = map.get("key");

Now, you decalre this Object in a Optional way :


Optional<Object> value = Optional.ofNullable(map.get("key"));

Be careful, Optional has lots of sub Classes like OptionalInt、OptionalLong and OptionalDouble, So Don't try to use Optional<Integer> . Below is another exmaple of Optional encapsulation.


public static int readDuration(Map<String,String> props, String name) {
 return Optional.ofNullable(props.get(name))
   .flatMap(Car::stringToInt) // convert String into Int
   .filter(i -> i > 0) // filter those > 0
   .orElse(0); // if it throws exception or < 0, then make it == 0 
 }
 
public static Optional<Integer> stringToInt(String s) {
 try {
  return Optional.of(Integer.parseInt(s)); // convert String into Int
 } catch (NumberFormatException e) {
  return Optional.empty();
 }
}

Optional is quite new in Java, Even though It has a lot of fancy features, but we still don't use it so ofen as the performance degrade a lot when we use Optional in real projects.


No comments:

Post a Comment

Add Loading Spinner for web request.

when web page is busily loading. normally we need to add a spinner for the user to kill their waiting impatience. Here, 2 steps we need to d...