Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning default value in method if there are no matches

I have a method that will find an operator and return the new position.

public Integer findToken(Character operator) {
    try {
        return tokenList.stream()
                .filter(x -> {
                    return x.position >= startPosition &&
                            x.position <= endPosition &&
                            x.operator == operator;
                })
                .findFirst().get()
                .position;
    } catch (Exception ex) {
        return null;
    }
} 

But if there are no matches, i want it to keep the old value.

startPosition = findToken(Operator.value);

How do i return the old value ? i tried giving a new parameter with the value in the method and passing it in the exception but then the code looks ugly. Is there a better way ?

like image 510
light speed Avatar asked Oct 22 '25 06:10

light speed


2 Answers

You may want to use orElse() method.
Store the result till findFirst in temporary variable and then perform other operations and return.
For Instance

    List<Integer> values = Arrays.asList(2, 4, 5, 6, 7, 1); 
    Integer i= values.stream()
                     .filter(x->x<1)
                     .findFirst().orElse(0);

    System.out.println(i);
like image 170
Shubham Chaurasia Avatar answered Oct 23 '25 19:10

Shubham Chaurasia


Doing the assignment that way, it is not possible unless you pass the old value as parameter.

What you can do is to change the assignment to use the Optional to take care of the null case:

Optional.ofNullable(findToken('*'))
        .ifPresent(pos -> startPosition = pos);

Also, it would probability make more sense to use the Optional to make it more explicit that the method findToken may not return a value:

public Optional<Integer> findToken(Character operator) {
    return tokenList.stream()
            .filter(x ->
                 x.position >= startPosition &&
                 x.position <= endPosition &&
                 x.operator == operator
            )
            .findFirst()
            .map(t -> t.position);
}

In such case, the assignment would be:

findToken('*').ifPresent(pos -> startPosition = pos);
like image 35
Helder Pereira Avatar answered Oct 23 '25 20:10

Helder Pereira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!