Fundamentals 8 min read

Master Java Method References and Optional: A Practical Guide

This article explains Java method references, static and instance forms, constructor references, and the Optional class with code examples, showing how to write concise, null‑safe functional code using Java 8 features.

Programmer DD
Programmer DD
Programmer DD
Master Java Method References and Optional: A Practical Guide

Simplify

Method references are expressed with a double colon :: and provide an alternative syntax for functional interfaces.

Static method reference: ClassName::staticMethod (e.g., Integer::parseInt)

Instance method reference: instance::method (e.g., str::substring)

Constructor reference: ClassName::new (e.g., User::new)

Method References

public final class Integer {
    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }
}

Assign a method reference to a variable, e.g., Function<String,Integer> fun = Integer::parseInt; Lambda expressions also implement functional interfaces, but method references directly reuse existing methods.

public class User {
    private String username;
    private Integer age;
    // constructors, toString, etc.
}

public static void main(String[] args) {
    // static method reference
    Function<String,Integer> fun = Integer::parseInt;
    Integer value = fun.apply("123");
    System.out.println(value);

    // instance method reference
    String content = "Hello JDK8";
    Function<Integer,String> func = content::substring;
    String result = func.apply(1);
    System.out.println(result);

    // constructor reference
    BiFunction<String,Integer,User> biFunction = User::new;
    User user = biFunction.apply("mengday",28);
    System.out.println(user.toString());

    // method reference as parameter
    sayHello(String::toUpperCase,"hello");
}

private static void sayHello(Function<String,String> func, String parameter) {
    String result = func.apply(parameter);
    System.out.println(result);
}

Optional Values

Java 8 introduced Optional to avoid null‑pointer exceptions. The class provides static factory methods of, ofNullable, and empty, as well as methods like get, isPresent, ifPresent, filter, map, flatMap, orElse, orElseGet, and orElseThrow.

public final class Optional<T> {
    private static final Optional<?> EMPTY = new Optional<>();
    private final T value;
    private Optional() { this.value = null; }
    private Optional(T value) { this.value = Objects.requireNonNull(value); }
    public static <T> Optional<T> empty() { return (Optional<T>) EMPTY; }
    public static <T> Optional<T> of(T value) { return new Optional<>(value); }
    public static <T> Optional<T> ofNullable(T value) { return value == null ? empty() : of(value); }
    public T get() { if (value == null) throw new NoSuchElementException("No value present"); return value; }
    public boolean isPresent() { return value != null; }
    public void ifPresent(Consumer<? super T> consumer) { if (value != null) consumer.accept(value); }
    public Optional<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate); return !isPresent() ? this : predicate.test(value) ? this : empty(); }
    public <U> Optional<U> map(Function<? super T, ? extends U> mapper) { Objects.requireNonNull(mapper); return !isPresent() ? empty() : Optional.ofNullable(mapper.apply(value)); }
    public <U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) { Objects.requireNonNull(mapper); return !isPresent() ? empty() : Objects.requireNonNull(mapper.apply(value)); }
    public T orElse(T other) { return value != null ? value : other; }
    public T orElseGet(Supplier<? extends T> other) { return value != null ? value : other.get(); }
    public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X { if (value != null) return value; else throw exceptionSupplier.get(); }
}

Using Optional makes code more robust by handling absent values explicitly.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaLambdaoptionalFunctionalInterfaceMethodReference
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.