Answer the question
In order to leave comments, you need to log in
Does the Java 8-* standard distribution have a ternary operator (condition? result_true: result_false) with lambdas?
Hello. It would be convenient if in Java (first of all, the 8th version is of interest) there would be a functional replacement for the ternary operator "condition ? result_true : result_false".
I can write it myself, but why do it if it probably already exists. Maybe someone found such methods in the standard delivery.
ZY Something like this:
class TernaryOperator<T> {
public static T run(boolean condition, Getter<T> resultIfTrue, Getter<T> resultIfFalse) {
return condition ? resultIfTrue.get() : resultIfFalse.get();
}
}
interface Getter<T> {
T get();
}
if (!requestTypeEntity.isPresent()) {
logger.error("There is no request type with id = " + reqTypeId);
return EMPTY_VALUE;
}
return requestTypeEntity.map(RefRequestTypeEntity::getTypeName).orElse(EMPTY_VALUE);
return TernaryOperator.run(!requestTypeEntity.isPresent(),
() -> {
logger.error("There is no request type with id = " + reqTypeId);
return EMPTY_VALUE;
}, () -> {
requestTypeEntity.map(RefRequestTypeEntity::getTypeName).orElse(EMPTY_VALUE);
})
Answer the question
In order to leave comments, you need to log in
The nine has Optional.ifPresentOrElse() and Optional.or() . In the eight you have to dodge:
1. Use Optional.orElseGet()
2. Use something like
requestTypeEntity.<Supplier>map(value -> () -> value)
.orElse(() -> {
logger.error("There is no request type with id = " + reqTypeId);
return EMPTY_VALUE;
})
.get();
Is there a standard
condition? result_true : result_false
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question