【问题标题】:Replacing isPresent with ifPresent and orElse用 ifPresent 和 orElse 替换 isPresent
【发布时间】:2020-09-08 23:40:27
【问题描述】:

我的方法中有以下逻辑,我检查可选参数的值,并根据它构建另一个对象。

AtomicReference<Employee> employeeValue = null;
    questions.forEach(question -> {
        if(question.isBoolean().isPresent()) {
            employeeValue.set(Employee.builder()
                    .withBooleanValue(Boolean.valueOf(question.value()))
                    .build());
        } else {
            employeeValue.set(Employee.builder()
                    .withStringValue(question.value())
                    .build());
        }
        Record record = Record.builder()
                .withId(question.id())
                .withValue(employeeValue.get())
                .build();
        answers.add(record);
    });

如何用 ifPresent 和 orElse 替换上述内容?我正在使用 Java 8,因此 ifPresentOrElse 方法不可用。如果我将 ifPresent 和 orElse 分别与匿名内部函数一起使用,我该怎么做?

任何帮助将不胜感激。

【问题讨论】:

    标签: java if-statement lambda optional


    【解决方案1】:

    您既不需要isPresent(),也不需要ifPresent()。您不需要peek()(如另一个答案)或AtomicReference(如问题)。我相信这样做:

        questions.forEach(question -> {
            Employee empl = question.isBoolean()
                    .map(b -> Employee.builder()
                            .withBooleanValue(Boolean.valueOf(question.value()))
                            .build())
                    .orElseGet(() -> Employee.builder()
                            .withStringValue(question.value())
                            .build());
            Record record = Record.builder()
                    .withId(question.id())
                    .withValue(empl)
                    .build();
            answers.add(record);
        });
    

    如果您愿意,您可以在另一个答案的流中应用这个想法。而不是使用Stream.forEach(),我更愿意收集到一个像列表这样的集合中,然后使用answers.addAll()

    【讨论】:

    • 这是一个很好的选择!非常感谢您的指导
    【解决方案2】:

    您可以通过questions 流式传输并使用peekmap-orElse 构造来实现相同的结果:

    questions.stream()
        .peek(question -> {
                Employee employee = question.isBoolean()
                    .map(b -> Employee.builder().withBooleanValue(Boolean.valueOf(question.value())).build())
                    .orElse(Employee.builder().withStringValue(question.value()).build());
                employeeValue.set(employee);
            }
        )
        .map(question -> Record.builder().withId(question.id()).withValue(employeeValue.get()).build())
        .forEach(answers.add(answer)); // did you mean 'record'?
        
    

    但老实说,它并没有太大变化 - 你的实现看起来可能不那么“java 八分之一”,但很好:)

    【讨论】:

    • 非常感谢您的回答。但是我得到'无法解析方法或ElseGet()。那条线是不是少了什么?
    • 是的,你是对的 - 在 java8 中你需要使用 map-orElse 构造 - 我已经更新了答案
    • 是的,问题是orElseGetOptional 的方法,因此在调用ifPresent 后不再可用
    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    相关资源
    最近更新 更多