GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Java Optional - working with Optional in Java Java Optionallast modified August 22, 2026
In this article we learn how to create, inspect, transform, and read
Optional is a container object that may or may not contain a value.
An
The
The examples use Java 25's compact source-file syntax. With an earlier Java
version, place the code inside a class and use a conventional
var empty = Optional.<String>empty();
We create an empty var word = Optional.of("falcon");
var word = Optional.ofNullable(value);
Simple example
In the following example, we have a simple example with Main.java
void main() {
var words = Arrays.asList("rock", null, "mountain",
null, "falcon", "sky");
for (var value : words) {
var word = Optional.ofNullable(value);
word.ifPresent(System.out::println);
}
}
We have a list of words; the list also contains Optional<String> word = Optional.ofNullable(words.get(i));
We know that we can get a word.ifPresent(System.out::println);
We print the value only when the
In the following example, we have three methods that return an
Main.java
void main() {
if (getNullMessage().isPresent()) {
System.out.println(getNullMessage().get());
} else {
System.out.println("n/a");
}
if (getEmptyMessage().isPresent()) {
System.out.println(getEmptyMessage().get());
} else {
System.out.println("n/a");
}
if (getCustomMessage().isPresent()) {
System.out.println(getCustomMessage().get());
} else {
System.out.println("n/a");
}
}
Optional<String> getNullMessage() {
return Optional.ofNullable(null);
}
Optional<String> getEmptyMessage() {
return Optional.empty();
}
Optional<String> getCustomMessage() {
return Optional.of("Hello there!");
}
The three methods return a null message, an empty message and a real message. if (getNullMessage().isPresent()) {
System.out.println(getNullMessage().get());
} else {
System.out.println("n/a");
}
First, we check if the value returned by the method contains a value with
Optional isEmpty
The Main.java
void main() {
var words = Arrays.asList("rock", null, "mountain",
null, "falcon", "sky");
for (var value : words) {
var word = Optional.ofNullable(value);
if (word.isEmpty()) {
System.out.println("n/a");
} else {
System.out.println(word.get());
}
}
}
In the example, we print Optional orElse
The Main.java
void main() {
System.out.println(getNullMessage().orElse("n/a"));
System.out.println(getEmptyMessage().orElse("n/a"));
System.out.println(getCustomMessage().orElse("n/a"));
}
Optional<String> getNullMessage() {
return Optional.ofNullable(null);
}
Optional<String> getEmptyMessage() {
return Optional.empty();
}
Optional<String> getCustomMessage() {
return Optional.of("Hello there!");
}
We managed to shorten the example a bit with
The expression passed to var word = Optional.of("falcon");
var result = word.orElseGet(() -> "n/a");
Use var word = Optional.of("falcon").orElseThrow();
Optional map
The Main.java
void main() {
var word = Optional.of("falcon");
var length = word.map(String::length);
length.ifPresent(System.out::println);
}
Here, Optional flatMap
The Main.java
void main() {
Function<String, Optional<String>> upperCase = s -> Optional.of(s.toUpperCase());
var words = Arrays.asList("rock", null, "mountain",
null, "falcon", "sky");
for (var value : words) {
var word = Optional.ofNullable(value);
var res = word.flatMap(upperCase);
res.ifPresent(System.out::println);
}
}
In this example, we apply the JSoup exampleIn the following example, we use JSoup library to parse and modify an HTML document.
For the project, we need the Main.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
void main() {
String htmlString = """
<html>
<head>
<title>My title</title>
</head>
<body>
<main></main>
</body>
</html>
""";
var doc = Jsoup.parse(htmlString);
var mainEl = Optional.ofNullable(doc.select("main").first());
mainEl.ifPresent(e -> {
e.append("<p>hello there!</p>");
e.prepend("<h1>Heading</h1>");
});
System.out.println(doc);
}
We parse an HTML string and look for the var doc = Jsoup.parse(htmlString);
Optional<Element> mainEl = Optional.ofNullable(doc.select("main").first());
The mainEl.ifPresent(e -> {
e.append("<p>hello there!</p>");
e.prepend("<h1>Heading</h1>");
});
We only call Jdbi example
The
For the example, we need the Main.java
import org.jdbi.v3.core.Jdbi;
void main() {
var jdbcUrl = "jdbc:postgresql://localhost:5432/testdb";
var user = "postgres";
var password = "your-password";
var jdbi = Jdbi.create(jdbcUrl, user, password);
var id = 3;
var query = "SELECT name FROM cars WHERE id = ?";
var res = jdbi.withHandle(handle -> handle.select(query, id)
.mapTo(String.class)
.findOne());
res.ifPresentOrElse(System.out::println, () -> System.out.println("N/A"));
}
In the example, we select a single cell from a row in a table. We print the data
if it is present or SourceJava Optional - language reference AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Java tutorials. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |