Dimitri Danilov Dimitri Danilov - 15 days ago 5
C++ Question

How can I avoid to do a lot of if's in java ?

In c++, I would use a map of int/pointer to function like this :

std::map = {
{Code::Value1, Handler::value1Handler},
{Code::Value2, Handler::value2Handler},
};


To avoid to do a lot of if's like

if (value == Code::Value1)
value1Handler();
if (value == Code::Value2)
value2Handler();
if (value == Code::Value3)
value3Handler();


But I didn't find a good way to do this in Java, is it possible ?

Answer

As I realised, you want to associate a key T with a corresponding action Consumer<T> (or a Function<K, V> if a return type matters).

Unfortunately, we don't have a map literal, so for short it's possible to generate a HashMap subclass with a init block:

Map<T, Consumer<T>> map = new HashMap<T, Consumer<T>>() {{
    put(k1, v -> {/* value handler 1 */});
    put(k2, v -> {/* value handler 2 */});
}};

As a map value, you can pass an action which you want to perform with a key. For instance,

v -> System.out.println(v)

If such an action is single, it can be replaced by a method reference:

System.out::println

(Here I comprehended that valueXHandlers return a map value, they aren't just consumers. Therefore, Function<K, V> is our way)

Normally, I would write a mapper which transforms a key to a value and returns that value:

public <K, V> V mapToValue(K key, Function<K, V> function) {
    return function.apply(key);
}

Its usage is simple enough:

map.put(k1, mapToValue(k1, k1 -> v1));
Comments