How-To
1. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>albert</groupId> <artifactId>test</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>test</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project>
2. Create a Person class
package albert.test; import lombok.Builder; import lombok.Data; import lombok.ToString; @Data @Builder @ToString public class Person { private Integer id; private String name; private String gender; }
3. Create a custom exception
package albert.test; public class PersonNotFoundException extends Exception { public PersonNotFoundException() { super(); } public PersonNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public PersonNotFoundException(String message, Throwable cause) { super(message, cause); } public PersonNotFoundException(String message) { super(message); } public PersonNotFoundException(Throwable cause) { super(cause); } }
4. Create a OptionalTest class
package albert.test; import java.util.Arrays; import java.util.List; import java.util.Optional; public class OptionalTest { private Person albert = Person.builder().id(1).name("Albert").gender("Male").build(); private Person mandy = Person.builder().id(2).name("Mandy").gender("Female").build(); private Person eric = Person.builder().id(3).name("Graham").gender("Male").build(); private List<Person> people = Arrays.asList(albert, mandy, eric); public Person getByNameByOldWay(String name) throws PersonNotFoundException { Person result = null; for (Person p : people) { if (p.getName().equals(name)) { result = p; break; } } if (result == null) { throw new PersonNotFoundException("Cannot find " + name); } return result; } public Person getByNameOrElseThrow(String name) throws PersonNotFoundException { Optional<Person> person = people.stream().filter(p -> name.equals(p.getName())).findFirst(); return person.isPresent() ? person.get() : person.orElseThrow(() -> new PersonNotFoundException("Cannot find " + name)); } }
Reference
[1] Optional in Java 8 cheat sheet