Dimitri Danilov Dimitri Danilov - 8 months ago 38
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)
if (value == Code::Value2)
if (value == Code::Value3)

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

Answer Source

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:


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