M
M
MaxLich2018-12-28 15:20:58
Java
MaxLich, 2018-12-28 15:20:58

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();
}

Usage.
Source:
if (!requestTypeEntity.isPresent()) {
            logger.error("There is no request type with id = " + reqTypeId);
            return EMPTY_VALUE;
        }

        return requestTypeEntity.map(RefRequestTypeEntity::getTypeName).orElse(EMPTY_VALUE);

Can be replaced with something like this:
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

2 answer(s)
S
Sergey Gornostaev, 2018-12-28
@sergey-gornostaev

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();

Or collect your functional interface. Although, the very desire to think something like this looks like crutches for pulling an imperative style onto a functional one.

D
Dmitry Alexandrov, 2018-12-28
@jamakasi666

Is there a standard
condition? result_true : result_false

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question