🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional. ... This method supports post-processing on optional values, without the need to explicitly check for a return status.
Discussions

Viewing Optional as a Replacement for Checked Exceptions
Optional isn't a replacement for checked exceptions, it's a replacement for null return values. Like null, Optional doesn't tell you why a method couldn't return a value. The actual replacement for checked exceptions, which Java doesn't have, is an Either type. The Either type behaves like Optional by short-circuiting the operation on failure, but more crucially, includes the reason why as a type. The error type is typically an algebraic type, which enumerates all the ways in which the operation can fail, so you can pattern match on the error. Thus, the Either type does both the things that checked exceptions do, putting the error types in the method signature and allowing catch-like constructs to match the error types. More on reddit.com
🌐 r/java
40
7
February 19, 2022
java - How can I map Optional to another Optional if not present? - Stack Overflow
I have tried with orElseGet but it doesn't allow to return another Optional but a User. ... See here: stackoverflow.com/questions/28818506/…. There are answers for both JDK 8 and 9. See the answer by @Misha, here: stackoverflow.com/a/28821352. ... This really should be closed as a duplicate but I have no more flags .^. ... Since Java ... More on stackoverflow.com
🌐 stackoverflow.com
java - Using Optional to map and return data which is not used - Stack Overflow
I am reusing the following optional optionalData which is declared and validated a few lines above. If I reach here, this optional is definitely not empty. The following code works fine as intended... More on stackoverflow.com
🌐 stackoverflow.com
Functional style of Java 8's Optional.ifPresent and if-not-Present? - Stack Overflow
@smallufo: replace return null; with return o; (both). However, I have the strong feeling that you are working at the wrong place. You should work at the site which produced that Optional. At that place there should be a way of performing the desired operation without the intermediate Optional. ... Java ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Medium
medium.com › @AlexanderObregon › javas-optional-map-method-explained-0a19206d6704
Java’s Optional.map() Method Explained | Medium
November 9, 2024 - It allows you to apply a transformation function to an Optional object only if it contains a value. If the Optional is empty, map() simply returns an empty Optional, skipping the function entirely.
🌐
Coderanch
coderanch.com › t › 687191 › reactive › paradigms › map-return
use .map() without return? (reactive forum at Coderanch)
You will see it takes a T as its parameter and returns an R. That determines how you have to implement it: you must supply one parameter which is the T and it must return an R. So no, you cannot implement Function#apply without returning something. This is how you might implement it as an anonymous ...
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - Notice that the filter method simply performs a check on the value and returns an Optional describing this value only if it matches the given predicate. Otherwise returns an empty Optional. The map method however takes the existing value, performs a computation using this value, and returns the result of the computation wrapped in an Optional object:
🌐
Readthedocs
java8tips.readthedocs.io › en › stable › optional.html
10. Handling nulls with Optional — Java 8 tips 1.0 documentation
Similar to Stream.map method, this is also commonly used as transformation function. This method supports post-processing on optional values, without the need to explicitly check for a return status.
🌐
Verhoevenv
verhoevenv.github.io › 2016 › 08 › 30 › TIL-Optional-map.html
Today I Learned: Java 8's Optional.map is actually flatmap | Vincent Verhoeven's blog
August 30, 2016 - However, on trying to explain what the flatMap does and why we need it, I stumbled upon an unexpected feature of Java. You might have already discovered it when experimenting with the codebase. It turns out the following is functionally equivalent, as proven by the tests we had written before we tried the whole refactoring: return Optional.ofNullable(location) .map(loc -> officeRepository.findFor(loc.getZipCode())) .orElseGet(() -> retrieveDefaultOffice());
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
Find elsewhere
🌐
Oracle
docs.oracle.com › en › java › javase › 14 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 14 & JDK 14)
If the mapping function returns a null result then this method returns an empty Optional. ... This method supports post-processing on Optional values, without the need to explicitly check for a return status.
🌐
Oracle
docs.oracle.com › javase › 9 › docs › api › java › util › Optional.html
Optional (Java SE 9 & JDK 9 )
If the mapping function returns a null result then this method returns an empty Optional. ... This method supports post-processing on Optional values, without the need to explicitly check for a return status.
🌐
Apps Developer Blog
appsdeveloperblog.com › home › java › functional programming in java › optional – map() and flatmap() operations
Optional - map() and flatMap() operations - Apps Developer Blog
August 10, 2022 - class Test { public static void main(String[] args) { Student student = new Student("John", "Smith", 8); student.setAddress(Optional.of("5th Avenue, New York")); Optional<Student> studentOptional = Optional.ofNullable(student); studentOptional .filter(s1 -> s1.getGrade() > 7) // returns Optional<Student[fName, lName, grade, Optional<String> address]> .flatMap(s1 -> s1.getAddress()) // returns Optional<String> .ifPresent(item -> System.out.println(item)); } } ... We got the actual value in the output since the flatMap() operation flattened/unpacked the Optional parameter. That was all about the map() and flatMap() operations from the Optional class in Java.
🌐
Evojam
evojam.com › technology-blog › 2021 › 4 › 28 › tackling-accidental-complexity-with-optional-in-java
Tackling accidental complexity with Optional in Java — Evojam
April 28, 2021 - BicycleRack updateRack2(String carUuid, rackData updateDto) { Optional<BicycleRack> bicycleRack; Optional<Car> car = carRepository.findByUuid(carUuid); // (1) BicycleRack rack; if (car.isPresent()) { // (2) bicycleRack = Optional.ofNullable(car.get().getRack()); // (3) (...) Optional<BicycleRack> existingRack = car.map(Car::getRack); // (4) } // public<U> Optional<U> map(Function<? super T, ? extends U> mapper) { // Objects.requireNonNull(mapper); // if (!isPresent()) // return empty(); // else { // return Optional.ofNullable(mapper.apply(value)); // (5) // } // } After the attempt to fetch an existing car in line (1), and the check if it is present in line (2), comes line (3). The author of this code has adopted a defensive strategy, which is good. The danger of NullPointerExceptions in Java is real.
Address   62 Mickiewicza Warszawa, mazowieckie,
🌐
Reddit
reddit.com › r/java › viewing optional as a replacement for checked exceptions
r/java on Reddit: Viewing Optional as a Replacement for Checked Exceptions
February 19, 2022 -

I had this old post floating around that I never got to publishing. Maybe 8 years after Optional came out it's a bit late to try to clarify it, but my impression is that Optional has not been embraced the way it should be. The concept is clearly a central part of Kotlin, but I just don't see people writing methods that return Optional<T> as much as I would expect.

If you're interested, take a look and tell me how wrong I am:

https://www.pragmaticcoding.ca/java/optional

Top answer
1 of 5
32
Optional isn't a replacement for checked exceptions, it's a replacement for null return values. Like null, Optional doesn't tell you why a method couldn't return a value. The actual replacement for checked exceptions, which Java doesn't have, is an Either type. The Either type behaves like Optional by short-circuiting the operation on failure, but more crucially, includes the reason why as a type. The error type is typically an algebraic type, which enumerates all the ways in which the operation can fail, so you can pattern match on the error. Thus, the Either type does both the things that checked exceptions do, putting the error types in the method signature and allowing catch-like constructs to match the error types.
2 of 5
5
I dislike blog posts that first set up a strawman and then attack the strawman. if (Optional.ofNull(variable).isPresent()) then { No. It's 2022. You generally don't see code like this unless that piece of code was written by an intern 8 years ago and hasn't been touched since then ;) Exceptions and optionals solve completely different problems. Exceptions are, as their name describes, things that get thrown if something exceptional happens. So if you retrieve a customer by ID that's not there, and this is a situation that should not occur in your application, you STILL should thrown an exception and handle it where your exceptions are handled. It's basically the choice between returning a 204 and a 404 when a resource does not exist. Should it be possible or not? So I personally completely disagree with the core idea of this post. You're comparing apples and sheep.
🌐
Reverse Coding
reversecoding.net › java-8-optional-replace-get-examples
Java 8 Optional - Replace your get() calls | Reverse Coding
June 19, 2016 - We can focus on the success case, ... function returns an Optional of some <T>. flatMap() executes the transformation function like the map() but instead of returning Optional<Optional<T>> if will just return Optional<T>. Basically it flattens the Optional....
🌐
Medium
medium.com › @andrewMacmurray › javas-optional-type-and-dealing-with-null-2e8a088cd91f
Java’s Optional type and dealing with Null | by Andrew MacMurray | Medium
May 11, 2018 - We can do this using Java 8’s new lambda syntax: OptionalExample optionalMap = new OptionalExample();optionalMap.getData(1).map(data -> data.toUpperCase()); // Optional<"DATA AT 1"> Using .map we can apply a transformation to the data if it’s present, and do nothing if it’s not there. What about using that String somewhere else? When we finally want to extract the value we can use: optionalMap .get(1) .map(data -> data.toUpperCase()) .orElse("Data not found");
🌐
Coderanch
coderanch.com › t › 729004 › java › Collections-getters-return-Optional
Collections - Should their getters return Optional? (Beginning Java forum at Coderanch)
April 7, 2020 - Java collections or data structures often have a method to get a specific element in that collection. Such methods often return null if the element is not present in the collection. For example, Map.get(Object key) returns null if the map contains no mapping for the key. Should these methods be upgraded to return an Optional instead ?
🌐
DZone
dzone.com › coding › languages › 26 reasons why using optional correctly is not optional
26 Reasons Why Using Optional Correctly Is Not Optional
November 28, 2018 - Starting with Java 9, we can treat theOptionalinstance as aStreamby applyingOptional.stream()method. This is useful when you need to chain the Optional API with the Stream API. This method creates aStreamof one element or an emptyStream(ifOptionalis not present). Further, we can use all the methods that are available in the Stream API. ... // AVOID public List<Product> getProductList(List<String> productId) { return productId.stream() .map(this::fetchProductById) .filter(Optional::isPresent) .map(Optional::get) .collect(toList()); } public Optional<Product> fetchProductById(String id) { return Optional.ofNullable(...); }
Top answer
1 of 13
334

If you are using Java 9+, you can use ifPresentOrElse() method:

Copyopt.ifPresentOrElse(
   value -> System.out.println("Found: " + value),
   () -> System.out.println("Not found")
);
2 of 13
129

For me the answer of @Dane White is OK, first I did not like using Runnable but I could not find any alternatives.

Here another implementation I preferred more:

Copypublic class OptionalConsumer<T> {
    private Optional<T> optional;

    private OptionalConsumer(Optional<T> optional) {
        this.optional = optional;
    }

    public static <T> OptionalConsumer<T> of(Optional<T> optional) {
        return new OptionalConsumer<>(optional);
    }

    public OptionalConsumer<T> ifPresent(Consumer<T> c) {
        optional.ifPresent(c);
        return this;
    }

    public OptionalConsumer<T> ifNotPresent(Runnable r) {
        if (!optional.isPresent()) {
            r.run();
        }
        return this;
    }
}

Then:

CopyOptional<Any> o = Optional.of(...);
OptionalConsumer.of(o).ifPresent(s -> System.out.println("isPresent " + s))
                .ifNotPresent(() -> System.out.println("! isPresent"));

Update 1:

the above solution for the traditional way of development when you have the value and want to process it but what if I want to define the functionality and the execution will be then, check below enhancement;

Copypublic class OptionalConsumer<T> implements Consumer<Optional<T>> {
private final Consumer<T> c;
private final Runnable r;

public OptionalConsumer(Consumer<T> c, Runnable r) {
    super();
    this.c = c;
    this.r = r;
}

public static <T> OptionalConsumer<T> of(Consumer<T> c, Runnable r) {
    return new OptionalConsumer(c, r);
}

@Override
public void accept(Optional<T> t) {
    if (t.isPresent()) {
        c.accept(t.get());
    }
    else {
        r.run();
    }
}

Then could be used as:

CopyConsumer<Optional<Integer>> c = OptionalConsumer.of(
    System.out::println, 
    () -> System.out.println("Not fit")
);

IntStream.range(0, 100)
    .boxed()
    .map(i -> Optional.of(i)
    .filter(j -> j % 2 == 0))
    .forEach(c);

In this new code you have 3 things:

  1. can define the functionality before the existing of an object easy.
  2. not creating object reference for each Optional, only one, you have so less memory than less GC.
  3. it is implementing consumer for better usage with other components.

By the way, now its name is more descriptive it is actually Consumer<Optional<?>>