java8Optional 使用

发布于:2025-02-21 ⋅ 阅读:(25) ⋅ 点赞:(0)

一、示例

public class TestMain {


    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public static class Leader {

        private Long employeeId;
        private BigDecimal bonus;

    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public static class Employee {

        private Long id;
        private String name;
        private Boolean leader;

    }

    public static class FiltUtil {

        public void OptionalStudy() {
            Optional<Leader> leader = Optional.ofNullable(getEmployeeById(1L)
                    .filter(Employee::getLeader)
                    .map(Employee::getId)
                    .flatMap(this::getLeaderByEmployeeId)
                    .orElse(null));
            if (leader.isPresent()) {
                Optional.of(
                        leader.map(Leader::getBonus)
                                .map(bonus -> String.format("员工ID为1的leader奖金为:%s", bonus))
                                .orElse("员工ID为1的leader也没有奖金"))
                        .ifPresent(System.out::println);
            } else {
                System.out.println("员工ID为1的leader未找到,他可能只是一个基层员工,不配拥有奖金");
            }
        }

        private Optional<Employee> getEmployeeById(Long id) {
            //return Optional.of(new Employee(1L, "大老板", Boolean.TRUE));
            return Optional.of(new Employee(1L, "大老板", Boolean.FALSE));
        }

        private Optional<Leader> getLeaderByEmployeeId(Long employeeId) {
            //return employeeId == 1L ? Optional.of(new Leader(1L, BigDecimal.valueOf(1000000000))) : Optional.empty();
            return employeeId == 1L ? Optional.of(new Leader(1L, null)) : Optional.empty();
        }

    }

    public static void main(String[] args) {
//        FiltUtil filtUtil = new FiltUtil();
//        filtUtil.OptionalStudy();
        Employee employee = new Employee(null,"",true);
        //Optional.断言
//        Optional.ofNullable(employee.getId()).orElseThrow(()-> new IllegalArgumentException(String.format("%s人员的Id不能为NULL", employee.toString())));
        Optional.ofNullable(employee).filter(e-> StringUtil.isEmpty(e.getName())).orElseThrow(()-> new IllegalArgumentException(String.format("%s人员的name不能为空", employee.toString())));
        Optional.ofNullable(employee.getName()).orElseThrow(()-> new IllegalArgumentException(String.format("%s人员的name不能为空", employee.toString())));

        //Optional.非空判断
        Optional.ofNullable(employee).ifPresent(o -> o.setName("UNKNOW"));
        System.out.println(employee.toString());
    }
}