函数式编程2-Optional

作者: 汪云飞 分类: Java技术 发布时间: 2018-12-19 16:23

本节我们讲一下Optional的使用,Optional主要用来对null的处理,我们将常规需要判断null的对象用Optional包装起来。

1.获取Optional对象的静态方法

  • Optional.of(value):value必须不能为空,

示例:Optional<String> firstName = Optional.of(person.getFirstName());

  • Optional.ofNullable(value):value可以为空

示例:Optional<String> middleName = Optional.ofNullable(person.getMiddleName());

2.Optional对象的主要方法

  • get()

T get():获得Optional中的对象包装的value,Tvalue的类型.

示例:String firstNameGreetings = firstNameOptional.get()

  • isPresent()

boolean isPresent():判断Optional中的value是否存在,返回值是boolean.

示例:boolean isPresent = middleNameOptional.isPresent()

  • ifPresent

ifPresent(Consumer<? super T> consumer):如果Optional中的value存在,执行什么操作. 对比《函数式编程1-Lambda表达式》的FunctionBiFunction,这里的Consumer<T>接口接受一个入参T类型,没有返回值.

示例:

firstNameOptional.ifPresent(name -> {
                            String firstNameGreetings = firstNameOptional.get().toUpperCase();
                            log.info("hello " + firstNameGreetings);
                          })
  • map()

Optional<U> map(Function<? super T, ? extends U> mapper): 对Optional中的value(类型为T)进行处理并返回一个新的Optional<U>,U为返回值类型.

示例:

Optional<String> lastNameOptionalNew = lastNameOptional
								.map(name ->  name.toUpperCase());
  • orElse()

T orElse(T other):和get()一样获得value的值,区别是有value的时候返回value,没有value的时候返回other.

示例

String middleNameGreetings = middleNameOptional
					.map(name ->  name.toUpperCase())
					.orElse("no middle name")

3.完整示例

  • Person
@Data
public class Person {

    private String firstName;

    private String middleName;

    private String lastName;

}
@Bean
CommandLineRunner testOptional(){
    return p -> {
        Person person = new Person();

        person.setFirstName("Will");
        Optional<String> firstNameOptional = Optional.of(person.getFirstName());
        firstNameOptional.ifPresent(name -> {
                                        String firstNameGreetings = firstNameOptional.get().toUpperCase();
                                        log.info("hello " + firstNameGreetings);
                                      });



        Optional<String> middleNameOptional = Optional.ofNullable(person.getMiddleName());
        String middleNameGreetings = middleNameOptional
                .map(name ->  name.toUpperCase())
                .orElse("no middle name");
        log.info("hello " + middleNameGreetings);

        log.info(new Boolean(middleNameOptional.isPresent()).toString());


        person.setLastName("Smith");
        Optional<String> lastNameOptional = Optional.ofNullable(person.getLastName());
        Optional<String> lastNameOptionalNew = lastNameOptional
                                        .map(name ->  name.toUpperCase());
        log.info("hello " + lastNameOptionalNew.get());



    };
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注