Tag: The null size function returns a Val style function is required ash print
The Flatmap function of Java8 is to return an empty optional if there is a value for which the mapping function returns the optional type return value.
See the mapping functions are often only a sentence, even curly braces do not need to add, as follows:
String Personvalue = optional.ofnullable (Map.get ("person")) , optional.of (value.tostring (). Trim ())) . OrElse ("");
But what if you could throw an exception in the mapping function?
The method also uses Try/catch, but it must have a return value of returns, the return value type is optional, and the finally block is not recommended.
Public Static voidMain (string[] args) {Map<string, object> map =NewHashmap<>(); String value=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (NewDate ()); System.out.println (value); Map.put ("Time", value); String TimeValue= ""; if(Map.get ("time")! =NULL){ Try{Date Date=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Parse (Map.get ("Time"). ToString (). Trim ()); TimeValue=NewSimpleDateFormat ("yyyy mm month DD Day"). Format (date); } Catch(ParseException e) {e.printstacktrace (); }} System.out.println (TimeValue); String timeValue2= Optional.ofnullable (Map.get ("Time") . FlatMap ((value2)-{String ans= ""; Try{Date Date=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Parse (Map.get ("Time"). ToString (). Trim ()); Ans=NewSimpleDateFormat ("yyyy mm month DD Day"). Format (date); } Catch(ParseException e) {e.printstacktrace (); } returnoptional.of (ans); }). OrElse (""); System.out.println (timeValue2);}
If you finally change to a finally block, idea will warn you, although the result is fine.
Reports finally blocks which can not complete normally.
Java8 Flatmap How to handle a function with an exception