Returning the default value in the method if there is no match
I have a method that will find an operator and return a 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 is no match, I want to keep the same value.
startPosition = findToken(Operator.value);
How do I return the old value? I tried to give a new parameter with a value in the method and pass it to the exception, but then the code looks ugly. Is there a better way?
source to share
By making the assignment this way, it is not possible unless you pass the old value as a parameter.
What you can do is change the assignment to use Optional
to take care of the case null
:
Optional.ofNullable(findToken('*'))
.ifPresent(pos -> startPosition = pos);
Also, it would be wiser to use Optional
, to make it more explicit, that the method findToken
might 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 this case, the assignment will be:
findToken('*').ifPresent(pos -> startPosition = pos);
source to share
You can use the orElse () method .
Store the result before findFirst in a temporary variable and then do 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);
source to share