How can I avoid doing a lot of if in Java?

In C, I will use the mapping of int / pointer to implement such a function: @ h_ 404_ 7@

std::map = {
{Code::Value1,Handler::value1Handler},{Code::Value2,Handler::value2Handler},};
if (value == Code::Value1)
  value1Handler();
if (value == Code::Value2)
  value2Handler();
if (value == Code::Value3)
  value3Handler();

Solution

As I realized, you want to associate the key t with the corresponding operation consumer < T > (or function < K, V > if return type is important)@ H_ 404_ 7@

Map<T,Consumer<T>> map = new HashMap<T,Consumer<T>>() {{
    put(k1,v -> {/* value handler 1 */});
    put(k2,v -> {/* value handler 2 */});
}};
v -> System.out.println(v)
System.out::println
public <K,V> V mapToValue(K key,Function<K,V> function) {
    return function.apply(key);
}
map.put(k1,mapToValue(k1,k1 -> v1));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>