Java – when I need to be in optional Use optional. On orelse() When orelseget()
I need to make a clear explanation for this. Even if I am reading this link about differences, there is no clear definition So anyone can explain this to me in code
Solution
I think I'm beginning to understand your problem The order of execution with optional may be different from the order we use in procedural programming (the same is true for Java streams and other code using Lambdas)
I will use two examples from Eugene's answer:
o1.orElse(new MyObject()); // 1055e4af
This is normal old Java: it is a call to orelse () with the new MyObject () as a parameter So first evaluate the parameters and create a new MyObject Then pass it to orelse() Orelse() check whether there is a value in optional; If so, it returns the value (discarding the newly created object); If not, it returns the object given in the parameter This is a simpler example
o1.orElseGet(() -> { System.out.println("Should I see this"); return new MyObject(); });
We use a parameter for the method call again and calculate the parameter first again Lambda is created and passed only as a supplier The code in {} has not been executed (you can't see whether I should see this in Eugene's output) Again, orelseget will check whether there is a value in optional If yes, this value is returned and the supplier we passed is ignored If not, call the vendor and execute the code in {} to get the value returned from orelseget()
In the first case, it can be said that MyObject is created and wasted Second, create and waste suppliers The reward you get is concise and null pointer safe code in both cases So it doesn't matter which one you choose If creating MyObject is expensive or has unnecessary side effects, of course you need a second version, where the object is created only when requested and will never be wasted Eugene in the comment mentioned that the returned object came from the database call Database calls are often time - consuming and you don't want to do anything