Home >Java >javaTutorial >Java 8——Optional
This article mainly introduces the simple use of Optional
of Java 8
1
2
3
4
5
6
7
|
public class Address {
##private String province;
private String city;
}
|
23456789101112131415161718 | @Test(expected = NoSuchElementException.class)
##public void emptyTest() { //Declare an empty Optional object
Optional nameOptional = Optional.empty();
// java.util.NoSuchElementException: No value present
nameOptional.get();}
public void ofNullTest() {// Create an Optional object based on the instance
Optional.of(new Address("Guangdong", "Zhongshan"));assertEquals(Optional.empty(), Optional.ofNullable(null));
// java.lang.NullPointerException Optional.of(null);
}
map
##1 2
|
The above is the detailed content of Java 8——Optional. For more information, please follow other related articles on the PHP Chinese website!