Optional Stream Skips Empty Slots
Flatten a list of Optional values with Optional.stream so empty slots vanish from the pipeline without any explicit isPresent check.
Code
import java.util.List;
import java.util.Optional;
public class Main {
record User(String name, Optional<String> nickname) {
}
public static void main(String[] args) {
List<User> users = List.of(
new User("ada", Optional.of("countess")),
new User("bob", Optional.empty()),
new User("cy", Optional.of("cyber")));
// Optional.stream yields zero or one element, so flatMap drops empties
List<String> nicknames = users.stream()
.flatMap(user -> user.nickname().stream())
.toList();
System.out.println("nicknames: " + nicknames);
long missing = users.stream()
.filter(user -> user.nickname().isEmpty())
.count();
System.out.println("users without nickname: " + missing);
// the same call chains after findFirst without an isPresent branch
String fallback = users.stream()
.filter(user -> user.name().startsWith("b"))
.findFirst()
.flatMap(User::nickname)
.orElse("none");
System.out.println("bob nickname: " + fallback);
}
}What the code does
All of the logic lives in the classes Main and User and the function main.
The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable. Optional wraps the possibly-absent value instead of a null sentinel.
Watch out for
- Nothing to add to the project before running it.
Using it
The main signature reads public static void main(String[] args)
The demo output is labeled (nicknames:, users without nickname:, bob nickname:), so every printed line maps back to its originating operation.
Key statements
.filter(user -> user.name().startsWith("b"))
.findFirst()
.flatMap(User::nickname)
.orElse("none");
.flatMap(user -> user.nickname().stream())
.toList();
.filter(user -> user.nickname().isEmpty())
.count();
Interactive Tools for This Topic
FAQ
- What does Optional Stream Skips Empty Slots print when run?
- The script runs standalone; its 3 labeled outputs include `nicknames:`, `users without nickname:`, `bob nickname:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.