brief introduction : In previous version development , We often use null To make a judgment to solve the problem NullPointerException problem , from 8 start , Introduced Optional
class , Can be a container object with or without non null values , A good solution to null pointer exception . Let's take a look at some useful ways to help us work efficiently through code examples .
Class method :
Sample code :
public class OptionalTest { public static void main(String[] args) { Integer
num1= null; Integer num2 = 10; //ofNullable method - Return to a
Optional, If the specified value is not empty , Current value , Otherwise empty Optional Optional<Integer> a = Optional.ofNullable
(num1); //of method - Return to a Optional, If the specified value is not empty , Current value , otherwise NullPointerException Optional<
Integer> b = Optional.of(num2); System.out.println(OptionalTest.sum(a, b)); }
public static Integer sum(Optional<Integer> a, Optional<Integer> b){
//isPresent method - If there is a value return true, Otherwise false . System.out.println(" The first parameter value exists : " + a.
isPresent()); System.out.println(" The second parameter value exists : " + b.isPresent()); //orElse method -
If the value exists , Return to it , Otherwise return other Integer value1 = a.orElse(new Integer(0)); //get method -
Get value , Value needs to exist , Otherwise throw NoSuchElementException Integer value2 = b.get(); return value1 +
value2; } }
result :
Technology
Daily Recommendation