Granolaboy
Granolaboy

Reputation: 333

Java elegant way of executing methods until condition met

I have method with a variable listElement I initialize with null and want to execute up to 9 different methods on a certain list (the method input), until I find a value I can overwrite listElement with.

If it's not null anymore, I don't want to execute the rest of the methods. If none of the methods find a variable to overwrite with, I want to return null.

Sample:

    public XXX findListElement(List<XXX> listsOfxxx) {

    XXX listElement = null;

    listElement = firstMethod(listsOfxxx);
    listElement = secondMethod(listsOfxxx);
    listElement = thirdMethod(listsOfxxx);
    listElement = fourthMethod(listsOfxxx);
    listElement = fifthMethod(listsOfxxx);
    ...

    return listElement;
}

How do I skip the rest of the methods, if the first method already finds my variable? The idea behind this is checking Poker hand strength from Straight Flush to High Card, if I found a Straight Flush inside my list of possible combinations, I don't want to check for Four of a Kind, since they are beaten by the Straight Flush anyway. Then I can simply return the found Straight Flush as the strongest combination of that player.

Upvotes: 1

Views: 688

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200206

You should use the Streams API.

    return Stream.<Function<List<Xxx>, Xxx>>of(this::firstMethod,
                                               this::secondMethod,
                                               this::thirdMethod)
                 .map(f -> f.apply(listOfXxx))
                 .filter(Objects::nonNull)
                 .findFirst().orElse(null);

Upvotes: 4

gabor.harsanyi
gabor.harsanyi

Reputation: 599

I'd recommend you the chain of responsibility design pattern

Another examples:

Upvotes: 3

Related Questions