Reputation: 84786
I often see in vavr-based code:
...
.map(x -> {
if (someCondition(x)) {
return doWith(x);
} else {
return x;
}
})
...
Is there any way to eliminate this logic from map
call using some constructs? I find this if
condition awkward.
Upvotes: 4
Views: 381
Reputation: 21
How about case-match
like the following:
Iterator.range(0, 10)
.map(index -> Match(index).of(
Case($(n -> n % 2 == 0), "even"),
Case($(), "odd")
))
Upvotes: 0
Reputation: 182
My idea would be to wrap x with optional
.map(x -> Optional.ofNullable(x)
.filter(this::someCondition)
.map(this::doWith)
.orElse(x))
And this returns Optional<X>
so U need to handle it properly somewhere else
Upvotes: 3
Reputation: 21975
Either use the ternary operator if the conditions do not contain any logic or very little
.map(x -> someCondition(x) ? doWith(x) : x)
Or extract the logic within the map in a method
.map(ClassName::myXTreatmentMethod)
// or
.map(this::myXTreatmentMethod)
With myXTreatmentMethod
being
public X_Type myXTreatmentMethod(X_Type x) {
if (someCondition(x)) {
// some logic
return doWith(x);
}
return x;
}
Upvotes: 2
Reputation: 393841
Using the ternary conditional expression may look better:
.map(x -> someCondition(x) ? doWith(x) : x)
Upvotes: 4