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 ?
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With