繁体   English   中英

用 ifPresent 和 orElse 替换 isPresent

[英]Replacing isPresent with ifPresent and orElse

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

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 与匿名内部函数分开使用,我该怎么做?

任何帮助将非常感激。

您既不需要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()

您可以浏览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八式”但很好:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM