Java8的flatMap如何處理有異常的函數

來源:互聯網
上載者:User

標籤:null   size   函數返回   需要   val   style   函數   ash   print   

Java8的flatMap函數,作用是:如果有值,為其執行mapping函數返回Optional類型傳回值,否則返回空Optional。

見到的映射函數往往都只有一句話,連大括弧都不需要加的,如下:

String personValue = Optional.ofNullable(map.get("person"))        .flatMap((value) -> Optional.of(value.toString().trim()))        .orElse("");

 

可是如果映射函數裡,可能會拋出異常,該怎麼辦?
方法也是使用try/catch,但是一定要有傳回值return,傳回值類型是Optional,並且不建議使用finally塊。 

public static void main(String[] args) {    Map<String, Object> map = new HashMap<>();    String value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());    System.out.println(value);    map.put("time",value);    String timeValue = "";    if(map.get("time") != null){        try {            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(map.get("time").toString().trim());            timeValue = new SimpleDateFormat("yyyy年MM月dd日").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 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(map.get("time").toString().trim());                    ans = new SimpleDateFormat("yyyy年MM月dd日").format(date);                } catch (ParseException e) {                    e.printStackTrace();                }                return Optional.of(ans);            }) .orElse("");    System.out.println(timeValue2);}

 

如果最後改成finally塊,IDEA會出現警告,雖然結果沒問題

Reports finally blocks which can not complete normally.

 

Java8的flatMap如何處理有異常的函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.