Use the class name. For example:

latestEvent.map(AssetEvent::getTimestamp).ifPresent(latestList::add);

Assuming AssetEvent is the name of the class having the getTimestamp method.

Answer from Eran on Stack Overflow
🌐
Medium
medium.com › @mittulsharma07 › exploring-java-optional-class-method-reference-and-constructor-reference-6a5dfd7bf8b2
Exploring Java: Optional Class, Method Reference, and Constructor Reference | by Mittul Sharma | Medium
March 10, 2025 - Optional<String> name = names.stream() ... of unexpected crashes. ... Method references offer a concise alternative to lambda expressions when calling a specific method directly....
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
March 16, 2026 - the result of applying an Optional-bearing mapping function to the value of this Optional, if a value is present, otherwise an empty Optional ... Return the value if present, otherwise return other. ... Return the value if present, otherwise invoke other and return the result of that invocation.
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - The downside of this approach is that all of our get methods are always executed, regardless of where a non-empty Optional appears in the Stream. If we want to lazily evaluate the methods passed to Stream.of(), we need to use the method reference and the Supplier interface:
🌐
DZone
dzone.com › coding › java › considerations when returning java 8's optional from a method
Considerations When Returning Java 8's Optional From a Method
January 31, 2018 - When declaring that a Java method ... who writes this method from returning null. The returned Optional is a reference type and, like any reference type, can be null....
🌐
Medium
medium.com › @kumar.atul.2122 › java-8-lambda-functional-interface-method-reference-stream-api-and-optional-class-f685143635fb
Java 8: lambda, functional interface, method reference, Stream API and Optional class | by Atul Kumar | Medium
February 19, 2023 - The @FunctionalInterface annotation is optional but recommended, as it helps to prevent accidental addition of extra abstract methods to the interface. The interface defines a single abstract method, doSomething(), which takes no arguments and returns no value. Once you have defined a functional interface, you can use it to create lambda expressions and method references.
Find elsewhere
Top answer
1 of 2
2

What about use enum to declare all fields from Request and use it as common part of the code. I did not check it, this is only to show my approach:

public enum RequestField {
    PLANT_ID(Request::getPlantId, (val, campaign) -> campaign.plant.id::contains),
    TITLE(Request::getTitle, (val, campaign) -> campaign.title::containsIgnoreCase),
    CAMPAIGN_NUMBER(Request::getCampaignNumber, (val, campaign) -> campaign.campaignNumber::like),
    // ... more fields here ...
    ;

    private final Function<Request, Optional<Object>> get;
    private final BiFunction<Object, Campaign, BooleanExpression> map;

    RequestField(Function<Request, Object> get, BiFunction<Object, Campaign, BooleanExpression> map) {
        this.get = get.andThen(Optional::ofNullable);
        this.map = map;
    }

    public static List<BooleanExpression> getBooleanExpressions(Request request, Campaign campaign) {
        if (request == null)
            return Collections.emptyList();

        List<BooleanExpression> res = new LinkedList<>();

        for (RequestField field : values())
            field.get.apply(request)
                     .map(r -> field.map.apply(r, campaign))
                     .ifPresent(res::add);

        return res.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(res);
    }
}

And your client code will be looking like:

List<BooleanExpression> booleanExpressions = RequestField.getBooleanExpressions(request, campaign);

P.S. Your last code could be look like:

if (request.getLockVehicle() != null)
    expressionMapping.add(request.getLockVehicle() ? campaign.lockVehicle.isNotNull() : campaign.lockVehicle.isNull());
2 of 2
0

The aim of using Optional is informing who is calling that method / parameter that it could be null.

In the first part of your code, you are not getting any advantage from this, you are just rewriting some code wrapping it around Optional logic but, as you said, without any "reusable" purpose.

A useful way is using it as returning value of a method: for example, if you know that your title could be null, you can refactor your getter like

public Optional<String> getTitle(){
    return Optional.ofNullable(this.title); //I'm guessing the 'title' variable here
}

This will help you: every time you call getTitle() , you will know that could be null, because you are obtaining an Optional<String> instead of a String.

This will bring then you to:

request.getTitle().ifPresent(title-> title.doSomething())
// you can also add something like .orElse("anotherStringValue")

The second example could be reworked as the first one, making the return of getLockVehicle() as Optional<Boolean>, even if I suggest here setting that with a default value in your class, probably to false... Optional<Boolean> is pretty senseless imho

Hope this helps clearing your mind

🌐
Baeldung
baeldung.com › home › java › core java › method references in java
Method References in Java | Baeldung
March 26, 2025 - Finally, let’s explore how to create a no-operation function that can be referenced from a lambda expression. In this case, we’ll want to use a lambda expression without using its parameters. ... As it is a varargs method, it will work in any lambda expression, no matter the referenced object or number of parameters inferred.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java 8 method reference (with examples)
Java 8 Method Reference (with Examples)
May 29, 2024 - Since Java 8, in simplest words, the method references are a way to refer to methods or constructors without invoking them. Learn the syntax with examples.
🌐
Oracle
docs.oracle.com › javase › 9 › docs › api › java › util › Optional.html
Optional (Java SE 9 & JDK 9 )
Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors. A variable whose type is Optional should never itself be null; it should always point to an Optional instance.
🌐
Reddit
reddit.com › r/cpp › the case for std::optional of reference types and void
r/cpp on Reddit: The Case for std::optional of Reference Types and Void
September 4, 2022 - There are no optional references; a program is ill-formed if it instantiates an optional with a reference type. Alternatively, an optional of a std::reference_wrapper of type T may be used to hold a reference.
🌐
Indrek
blog.indrek.io › articles › misusing-java-optional
Misusing Java’s Optional type | That Which Inspires Awe
October 5, 2019 - When you see that a method returns ... that the method signature is trying to tell you that the return value might be missing. The good thing about Optionals is that they force you to handle the special case where there might be no value. Since Optionals are designed so that we don’t have to explicitly deal with null references anymore, returning ...
🌐
DEV Community
dev.to › sohailshah › using-optionals-in-java-the-right-way-4aho
Using Optional in Java the right way - DEV Community
August 21, 2023 - The java.util.Optional class is a generic type class that contains only one value of type T. Its purpose is to provide a safer alternative to reference objects of a type T that can be null.
🌐
IDRSolutions
blog.idrsolutions.com › home › java 8 method references explained in 5 minutes
Java 8 Method References explained in 5 minutes
June 28, 2024 - To use Lambda and Method Reference, make sure you have Java 8 installed. They do not work on Java 7 and earlier versions. If you found this article useful, you may also be interested in our other Java8 posts on Lambda Expression, Streams API, Default Methods, Consumer Suppliers, Optional and ...
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 11 & JDK 11 )
January 20, 2026 - Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors. A variable whose type is Optional should never itself be null; it should always point to an Optional instance.
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › methodreferences.html
Method References (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
See JDK Release Notes for information ... deprecated options for all JDK releases. You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing ...
🌐
cppreference.com
en.cppreference.com › cpp › utility › optional
std::optional - cppreference.com
Any instance of optional at any given point in time either contains a value or does not contain a value.
🌐
Guava
guava.dev › releases › 19.0 › api › docs › com › google › common › base › Optional.html
Optional (Guava: Google Core Libraries for Java 19.0 API)
A non-null Optional<T> reference can be used as a replacement for a nullable T reference. It allows you to represent "a T that must be present" and a "a T that might be absent" as two distinct types in your program, which can aid clarity. ... As a method return type, as an alternative to returning ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › csharp › programming-guide › classes-and-structs › named-and-optional-arguments
Named and Optional Arguments - C# | Microsoft Learn
The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. A nullable reference type (T?) allows arguments to be explicitly null but doesn't inherently make a parameter optional.