Considering the following code:
import java.util.Optional;
// one class needs to have a main() method
public class Test
{
public String orelesMethod() {
System.out.println("in the Method");
return "hello";
}
public void test() {
String value;
value = Optional.<String>ofNullable("test").orElseGet(this::orelesMethod);
System.out.println(value);
value = Optional.<String>ofNullable("test").orElse(orelesMethod());
System.out.println(value);
}
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
Test test = new Test();
test.test();
}
}
if we get value
in this way: Optional.<String>ofNullable(null)
, there is no difference between orElseGet() and orElse(), but if we get value
in this way: Optional.<String>ofNullable("test")
, orelesMethod()
in orElseGet()
will not be called but in orElse()
it will be called