Java8 Flatmap How to handle a function with an exception

Source: Internet
Author: User
Tags finally block

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.