Java 8 Optional

来自姬鸿昌的知识库
Jihongchang讨论 | 贡献2026年2月3日 (二) 14:44的版本
跳到导航 跳到搜索

示例1

public class OptionalTest {

    private User getUser() {
        return null;
    }

    @Test
    public void test1() {

        User user = getUser();

        String city = "未知";

        if (user!=null) {
            Address address = user.getAddress();
            if (address!=null) {
                city = address.getCity();
            }
        }

    }

    @Test
    public void test2() {
        Optional<User> optionalUser = Optional.ofNullable(getUser());

        String city = optionalUser
                .map(User::getAddress)
                .map(Address::getCity)
                .orElse("未知");

    }

}

示例2

package org.example.converter.excel;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.DateTimeFormatProperty;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.util.Optional;

public class LocalDateConverter implements Converter<LocalDate> {

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Class<?> supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalDate value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (value == null) {
            return new WriteCellData<>();
        }
        String format = Optional.ofNullable(contentProperty)
                .map(ExcelContentProperty::getDateTimeFormatProperty)
                .map(DateTimeFormatProperty::getFormat)
                .orElse(DatePattern.NORM_DATE_PATTERN);
        return new WriteCellData<>(LocalDateTimeUtil.format(value, format));
    }

    @Override
    public LocalDate convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        
        String stringValue = Optional.ofNullable(cellData)
                .map(ReadCellData::getStringValue)
                .orElse(null);

        if (StringUtils.isBlank(stringValue)) {
            return null;
        }

        return Optional.ofNullable(contentProperty)
                .map(ExcelContentProperty::getDateTimeFormatProperty)
                .map(DateTimeFormatProperty::getFormat)
                .filter(StringUtils::isNotBlank)
                .map(format -> LocalDateTimeUtil.parseDate(stringValue, format))
                .orElse(null);
    }
}