Opal
Opal

Reputation: 84786

if-logic elimination from map call

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

Answers (4)

Kevin Ip
Kevin Ip

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

johnykov
johnykov

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

Yassin Hajaj
Yassin Hajaj

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

Eran
Eran

Reputation: 393841

Using the ternary conditional expression may look better:

.map(x -> someCondition(x) ? doWith(x) : x)

Upvotes: 4

Related Questions