Consider following classes:
ClassA {
}
ClassB {
private ClassA classA;
// getters and setters
}
As there is no peek
method available on Optional
, is this considered abusing the Optional#map
method:
return myService.findA()
.flatMap(a -> myService.findB(a) // also returns optional
.map(b -> {
b.setClassA(a);
return b;
}))
.map(d -> MyType.of(d)) // MyType being other class
.orElse(MyType.empty());
This could also be written like this:
Optional<ClassA> optionalA = myService.findA();
if (optionalA.isPresent()) {
Optional<ClassB> optionalB = myService.findB(optionalA.get());
if (optionalB.isPresent()) {
ClassB classB = optionalB.get();
classB.setClassA(optionalA.get());
return MyType.of(classB);
}
return MyType.empty();
Both implementations perform the same logic, should one be preferred over the other ?