Skip to content

Instantly share code, notes, and snippets.

@martin-mok
Forked from kherge/Example.java
Created November 22, 2023 11:14
Show Gist options
  • Save martin-mok/3c688efcf31d8ff6028eb55612261bb0 to your computer and use it in GitHub Desktop.
Save martin-mok/3c688efcf31d8ff6028eb55612261bb0 to your computer and use it in GitHub Desktop.
Null Coalescing in Java

Null Coalescing in Java

At the time of this writing, Java does not provide a null coalescing operator. Fortunately, we can approximate the behavior by using Optional.

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.Optional;
public class Example {
public static void main(String []args) {
// Create a series of nullable objects.
Test a = new Test();
Test b = new Test();
Test c = new Test();
Test d = new Test();
a.setInner(b);
b.setInner(c);
c.setInner(d);
// This is probably as close as we're going to get to
// null coalescing without actual language support.
Optional
.ofNullable(a)
.map(i -> i.getInner())
.map(i -> i.getInner())
.map(i -> i.getInner())
.ifPresent(i -> i.hello());
// If you go too deep and find a `null`, nothing happens.
Optional
.ofNullable(a)
.map(i -> i.getInner())
.map(i -> i.getInner())
.map(i -> i.getInner())
.map(i -> i.getInner())
.map(i -> i.getInner())
.map(i -> i.getInner())
.ifPresent(i -> i.hello());
// You can also just retrieve a value instead of consuming the object.
String string = Optional
.ofNullable(a)
.map(i -> i.getInner())
.map(i -> i.getInner())
.map(i -> i.getInner())
.map(i -> i.toString())
.orElse("<is null>");
System.out.println(string);
}
private static class Test {
private Test inner;
public Test getInner() {
return inner;
}
public void hello() {
System.out.println("Hello, world!");
}
public void setInner(Test inner) {
this.inner = inner;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment