I have the following code in Java which I need to optimize by the usage of Optional in Java 8:
if (x.isEmpty() || x.contains("<")) { x = "hello1"; } else if (x.contains(",")) { x = "hello2"; } else { x = "hello3"; }
Can someone suggest a Java 8 based code using Optional?
I don’t want to use multiple if-else. I prefer using something more functional like Optional
in java 8 since if-else is more imperative style. So I can correct and say my objective is not in terms of code optimization in terms of performance, but making it use Java 8 standards which are more functional in nature.
Advertisement
Answer
x = x.isEmpty() || x.contains("<") ? "hello1" : x.contains(",") ? "hello2" : "hello3";
If you’re after the functional style that you can in some cases have with Optional
, then you still don’t need an Optional
in this case, but rather the good old conditional operator (sometimes called the ternary operator; it was there since Java 1.0). There would be no meaningful way to fit an Optional
into your code.