Java 8 - Difference between Optional.flatMap and Optional.map

后端 未结 6 623
感动是毒
感动是毒 2020-11-29 16:25

What\'s the difference between these two methods: Optional.flatMap() and Optional.map()?

An example would be appreciated.

6条回答
  •  不知归路
    2020-11-29 17:23

    Note:- below is the illustration of map and flatmap function, otherwise Optional is primarily designed to be used as a return type only.

    As you already may know Optional is a kind of container which may or may not contain a single object, so it can be used wherever you anticipate a null value(You may never see NPE if use Optional properly). For example if you have a method which expects a person object which may be nullable you may want to write the method something like this:

    void doSome(Optional person){
      /*and here you want to retrieve some property phone out of person
        you may write something like this:
      */
      Optional phone = person.map((p)->p.getPhone());
      phone.ifPresent((ph)->dial(ph));
    }
    class Person{
      private String phone;
      //setter, getters
    }
    

    Here you have returned a String type which is automatically wrapped in an Optional type.

    If person class looked like this, i.e. phone is also Optional

    class Person{
      private Optional phone;
      //setter,getter
    }
    

    In this case invoking map function will wrap the returned value in Optional and yield something like:

    Optional> 
    //And you may want Optional instead, here comes flatMap
    
    void doSome(Optional person){
      Optional phone = person.flatMap((p)->p.getPhone());
      phone.ifPresent((ph)->dial(ph));
    }
    

    PS; Never call get method (if you need to) on an Optional without checking it with isPresent() unless you can't live without NullPointerExceptions.

提交回复
热议问题