java optional code example
Example 1: check if optional is empty java
@Test
public void givenNull_whenCreatesNullable_thenCorrect() {
String name = null;
Optional<String> opt = Optional.ofNullable(name);
assertFalse(opt.isPresent());
}
Example 2: instantiate optinal java 8
Person p = new Person();
Optional<Person> op = Optional.of(p);
Example 3: check if optional is empty java
String o = getOptional().orElse(null);
if (o == null) {
return;
}
Example 4: java how to make a parameter optional
void foo(String a, Integer b) {
}
void foo(String a) {
foo(a, 0);
}
foo("a", 2);
foo("a");
Example 5: java how to make a parameter optional
class Foo {
private final String a;
private final Integer b;
Foo(String a, Integer b) {
this.a = a;
this.b = b;
}
}
class FooBuilder {
private String a = "";
private Integer b = 0;
FooBuilder setA(String a) {
this.a = a;
return this;
}
FooBuilder setB(Integer b) {
this.b = b;
return this;
}
Foo build() {
return new Foo(a, b);
}
}
Foo foo = new FooBuilder().setA("a").build();