2
2
.
.
3
3
.
.
3
3
O
O
p
p
t
t
i
i
o
o
n
n
a
a
l
l
I
I
n
n
f
f
o
o
In JAVA Optional is created using Generic Class java.util.Optional<T> which is a single-object container that either
● contains Object of given type
● doesn't contain an Object (it is said to be "empty")
Optional is alternative way of handling Variables that can be null in order to avoid null pointer exceptions during runtime.
Content
● Optional Syntax
● Optional Methods
● Combining Methods
O
O
p
p
t
t
i
i
o
o
n
n
a
a
l
l
S
S
y
y
n
n
t
t
a
a
x
x
Optional is declared by
● using Optional Class Optional Optional
● followed by <Data Type> <String>
● followed by Optional Name name
Optional Syntax
Optional<String> name = Optional.of("John");
Optional Syntax
import java.util.Optional;
public class Test {
public static void main(String args[]) {
Optional <String> name = Optional.of("John");
System.out.println(name); //Optional[John]
}
}
O
O
p
p
t
t
i
i
o
o
n
n
a
a
l
l
M
M
e
e
t
t
h
h
o
o
d
d
s
s
Optional Class has different Methods for creating, reading, transforming and analyzing its Instances.
Optional Methods
import java.util.Optional;
public class Test {
public static void main(String args[]) throws Exception {
//DECLARE OTPIONAL.
Optional<String> emptyString = Optional.empty(); //Create Optional that is empty
Optional<Integer> emptyInteger = Optional.empty(); //Create Optional that is empty
Optional<String> string = Optional.of("John"); //Create Optional that contains String
Optional<Integer> integer = Optional.of(new Integer(20)); //Create Optional that contains Integer
Optional<String> canBeNull = Optional.ofNullable("John"); //Create Optional with or without Object
Optional<String> nullOptional = Optional.ofNullable(null); //Create Optional with or without Object
//If Optional has Object return Object. Otherwise throws Exception.
String name1 = string .get();
//String nameEmpty = empty.get();
//If Optional has Object return Object. Otherwise return specified default value.
String name = string .orElse("unknown");
String nameEmpty = emptyString .orElse("unknown");
//If Optional has Object return Object. Otherwise return value returned by provided handler.
Integer age = integer .orElseGet(() -> { return 0; });
Integer ageEmpty = emptyInteger.orElseGet(() -> { return 0; });
//If Optional has Object return Object. Otherwise throw custom Exception.
Integer age2 = integer .orElseThrow( () -> { return new Exception("No value"); } );
//Integer ageEmpty2 = emptyInteger.orElseThrow( () -> { return new Exception("No value"); } );
//If Optional has Object return true. Otherwise return false.
boolean hasName1 = string .isPresent(); //true
boolean hasName2 = emptyString .isPresent(); //false
//If Optional has Object execute Handler that returns no value. Otherwise do nothing.
string.ifPresent( (value) -> { System.out.println("Value found - " + value); });
//Execute provided handler if Optional contains Object. Otherwise returns empty Optional.
//If handler returns true, filter() returns that same Optional. Otherwise returns empty Optional.
Optional<Integer> result1 = integer.filter( value -> {
if (value == 20) { return true; } //Optional[20]
else { return false; } //Optional.empty
});
//Returns Optional with a Value returned by handler.
Optional<Object> result2 = string.map( value -> {
return Optional.of("Your name is " + value); //Optional[Optional[Your name is John]]
});
//Returns Optional with a Value returned by handler.
//If handler would return Optional, its value is first taken out before returnig final Optional.
//Returns Optional<String> instead of Optional<Optional<String>>.
Optional<String> result3 = string.flatMap( value -> {
return Optional.of("Your name is " + value); //Optional[Your name is John]
});
//DISPLAY OPTIONAL.
System.out.println(emptyString); //Optional.empty
System.out.println(string); //Optional[John]
System.out.println(integer); //Optional[10]
//DISPLAY EXTRACTED OBJECTS.
System.out.println(name1); //John
System.out.println(name); //John
System.out.println(nameEmpty); //unknown
System.out.println(age); //20
System.out.println(ageEmpty); //0
System.out.println(age2); //20
System.out.println(hasName1); //true
System.out.println(hasName2); //false
System.out.println(result1); //Optional[20]
System.out.println(result2); //Optional[Optional[Your name is John]]
System.out.println(result3); //Optional[Your name is John]
}
}
C
C
o
o
m
m
b
b
i
i
n
n
i
i
n
n
g
g
M
M
e
e
t
t
h
h
o
o
d
d
s
s
You can combine filter() and ifPresent() to perform operation only if Optional Value matches filter criteria
import java.util.Optional;
public class Test {
public static void main(String[] args) throws Exception {
Optional<Integer> optional = Optional.of(new Integer(10));
optional
.filter ( value -> { if(value == 10) { return true; } else { return false; } } )
.ifPresent( value -> { System.out.println("Value found: " + value); } );
}
}
You can use map() to extract Instance Property and then combine filter() and ifPresent() on it as shown above
import java.util.Optional;
public class Test {
public static void main(String[] args) throws Exception {
//CREATE OPTIONAL.
Optional<User> optional = Optional.of(new User("Jack"));
//CREATE ANOTHER OPTIONAL.
optional
.map ( value -> { return value.name; } )
.filter ( value -> { if(value == "Jack") { return true; } else { return false; } } )
.ifPresent( value -> { System.out.println("Name found: " + value); } );
}
}
class User {
String name;
User(String name) {
this.name = name;
}
}
If Property of interest is Optional we can use flatMap() instead to extract actual value before applying filter() & ifPresent()
import java.util.Optional;
public class Test {
public static void main(String[] args) throws Exception {
//CREATE OPTIONAL.
Optional<User> optional = Optional.of(new User(Optional.of("Jack")));
//CREATE ANOTHER OPTIONAL.
optional
.flatMap ( value -> { return value.name; } )
.filter ( value -> { if(value == "Jack") { return true; } else { return false; } } )
.ifPresent( value -> { System.out.println("Name found: " + value); } );
}
}
class User {
Optional<String> name;
User(Optional<String> name) {
this.name = name;
}
}