当前位置: 首页 > 工具软件 > Optional > 使用案例 >

使用Optional代替繁琐的if else

郎慎之
2023-12-01

Optional的构造器是私有的

1、无参构造器和带参的构造器都是私有,所有这个创建Optional对象类似单例模式

    private Optional() {
        this.value = null;
    }
    /**
     * Constructs an instance with the value present.
     *
     * @param value the non-null value to be present
     * @throws NullPointerException if value is null
     */
    private Optional(T value) {
        this.value = Objects.requireNonNull(value);
    }

2、Optional中有个一个私有属性value

    /**
     * If non-null, the value; if null, indicates no value is present
     */
    private final T value;

3、通过of方式创建Optional对象,在这个方法里调用带参构造函数

    /**
     * Returns an {@code Optional} with the specified present non-null value.
     *
     * @param <T> the class of the value
     * @param value the value to be present, which must be non-null
     * @return an {@code Optional} with the value present
     * @throws NullPointerException if value is null
     */
    public static <T> Optional<T> of(T value) {
        return new Optional<>(value);
    }

4、获取Optional对象的value


    /**
     * If a value is present in this {@code Optional}, returns the value,
     * otherwise throws {@code NoSuchElementException}.
     *
     * @return the non-null value held by this {@code Optional}
     * @throws NoSuchElementException if there is no value present
     *
     * @see Optional#isPresent()
     */
    public T get() {
        if (value == null) {
            throw new NoSuchElementException("No value present");
        }
        return value;
    }

5、判断Optional对象中的value是否为null

    /**
     * Return {@code true} if there is a value present, otherwise {@code false}.
     *
     * @return {@code true} if there is a value present, otherwise {@code false}
     */
    public boolean isPresent() {
        return value != null;
    }

6、ifPresent,如果value不为空,则...,就是要干嘛

    /**
     * If a value is present, invoke the specified consumer with the value,
     * otherwise do nothing.
     *
     * @param consumer block to be executed if a value is present
     * @throws NullPointerException if value is present and {@code consumer} is
     * null
     */
    public void ifPresent(Consumer<? super T> consumer) {
        if (value != null)
            consumer.accept(value);
    }

示例:

一个Student类

package test;

public class Student {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
        Student s1 = new Student();
        s1.setName("张三锋");
        
        Optional<Student> o1 = Optional.of(s1);
        o1.ifPresent(item -> item.setName("我是" + item.getName()));
        System.out.println(o1.get().getName());

控制台输出:我是张三锋

还可以是集合类型

        Student s1 = new Student();
        s1.setName("张三锋");

        Student s2 = new Student();
        s2.setName("张无极");

        List<Student> studentList = new ArrayList<>();
        studentList.add(s1);
        studentList.add(s2);

        Optional<List<Student>> olist = Optional.of(studentList);
        olist.ifPresent(list ->{
            list.forEach(item ->{
                item.setName("你好" + item.getName());
            });
        });

        olist.ifPresent(list ->{
            list.forEach(item ->{
                System.out.println(item.getName());
            });
        });

控制台输出:

你好张三锋
你好张无极

7、map,获取对象属性值

    public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
        Objects.requireNonNull(mapper);
        if (!isPresent())
            return empty();
        else {
            return Optional.ofNullable(mapper.apply(value));
        }
    }

8、过滤

    /**
     * If a value is present, and the value matches the given predicate,
     * return an {@code Optional} describing the value, otherwise return an
     * empty {@code Optional}.
     *
     * @param predicate a predicate to apply to the value, if present
     * @return an {@code Optional} describing the value of this {@code Optional}
     * if a value is present and the value matches the given predicate,
     * otherwise an empty {@code Optional}
     * @throws NullPointerException if the predicate is null
     */
    public Optional<T> filter(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate);
        if (!isPresent())
            return this;
        else
            return predicate.test(value) ? this : empty();
    }

9、如果value为空,返回...

    /**
     * Return the value if present, otherwise return {@code other}.
     *
     * @param other the value to be returned if there is no value present, may
     * be null
     * @return the value, if present, otherwise {@code other}
     */
    public T orElse(T other) {
        return value != null ? value : other;
    }

示例:比如说有一个枚举,有code和msg两个属性,现在通过code获取msg。这里同时调用了map和orElse方法。

	enum MonitorStatus{
		NOT(1, "未开始"),
		ING (2, "进行中"),
		END(3, "已结束");
		private Integer code;
		private String msg;

		MonitorStatus(Integer code, String msg) {
			this.code = code;
			this.msg = msg;
		}

		public Integer getCode() {
			return code;
		}

		public String getMsg() {
			return msg;
		}

		public static String getEnum(Integer code) {
			return Arrays.stream(MonitorStatus.values()).filter(item -> item.getCode().equals(code)).findFirst().map(MonitorStatus::getMsg).orElse(null);
		}
	}

示例:用Optional替换if else操作

String tStr = "abc";
System.out.println(Optional.ofNullable(tStr).map(String::length).orElse(0));

List<String> list = null;
System.out.println(Optional.ofNullable(list).map(List::size).orElse(0));

 类似资料: