Java 8 Method References and Optional: Concise Coding with Functional Interfaces
This article introduces Java 8's method reference syntax and the Optional class, explaining static, instance, and constructor references, demonstrating their use with functional interfaces such as Function and BiFunction, and providing practical code examples to write more concise and null‑safe Java code.
Java 8 introduced method references and the Optional class to make code more concise and null‑safe.
1: Concise
Method references use the :: operator and serve as 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)
public final class Integer {
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
}Assigning a method reference to a variable of a functional interface type (e.g., Function<String,Integer> fun = Integer::parseInt) demonstrates that method references are a form of functional interface implementation.
2: Method References in Practice
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());
// passing method reference as argument
sayHello(String::toUpperCase, "hello");
}
private static void sayHello(Function<String, String> func, String parameter) {
System.out.println(func.apply(parameter));
}3: Optional – A Safer Alternative to Null
The Optional class, now part of the Java standard library, provides a container that may or may not hold a non‑null value, helping to avoid NullPointerException.
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 <U> Optional<U> map(Function<? super T, ? extends U> mapper) { return isPresent() ? Optional.ofNullable(mapper.apply(value)) : empty(); }
public <U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) { return isPresent() ? Objects.requireNonNull(mapper.apply(value)) : empty(); }
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(); }
}Typical usage:
String msg = "hello";
Optional<String> optional = Optional.of(msg);
boolean present = optional.isPresent();
String value = optional.get();
String hi = optional.orElse("hi");
optional.ifPresent(opt -> System.out.println(opt));These examples illustrate how method references and Optional can lead to more readable and robust Java code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
