我们有一个方法,它接收类层次结构顶部的类的对象。它使用基于层次结构中某个位置的字段的条件,如果满足该条件,则它为构建器使用另一个字段,该字段也在层次结构中的某个位置,但位于从顶级开始的不同路径上。public Optional<SomeType> create(final TopClassInHierarchy topClass) { Optional<SomeType> someObject = Optional.empty(); if (someCondition.evaluate(getFieldOne(topClass))) { someObject = Optional.of(new SomeType.Builder() .withFieldTwo(getFieldTwo(topClass)) .build()); } return someObject;private FieldOne getFieldOne(TopClassInHierarchy topClass) { return topClass.getSomething()...getFieldOne();private FieldTwo getFieldTwo(TopClassInHierarchy topClass) { return topClass.getSomethingElse()...getFieldTwo();我们希望最好将其浓缩为一个语句,例如这样SomeType.Builder builder = new SomeType.Builder();Optional.of(topClass) .map(this::getFieldOne) .filter(someCondition::evaluate) .map(this::getFieldTwo) //??? .ifPresent(builder::withFieldTwo);然而,一旦我们将 topClass 映射到 fieldOne 以进行条件评估,之后我们似乎无法“退回”到 topClass 以将其映射到 fieldTwo 以供构建器使用。这是否可行?
3 回答
幕布斯6054654
TA贡献1876条经验 获得超7个赞
你不应该说这样的话:
.map(x -> new SimpleEntry<>(this.getFieldOne(x), this.getFieldTwo(x)))
.filter(e -> evaluateTheCondition(e.getKey()))
.map(Entry::getValue)
.ifPresent(builder::withFieldTwo);
ITMISS
TA贡献1871条经验 获得超8个赞
由于您不需要 getFieldOne,因此您不应该映射到它,否则您将无法返回另一个 getFieldTwo 的映射;我建议你首先使用没有方法引用的过滤器,如果它评估为真映射 tto getFieldTwo:
Optional.of(entity) .filter(p->someCondition.evaluate(p.getSomething().getFieldOne())) .map(this::getFieldTwo) .ifPresent(builder::withFieldTwo);
添加回答
举报
0/150
提交
取消