使用Java 8替代的if语句

使用Java 8替代的if语句,java,if-statement,lambda,java-8,Java,If Statement,Lambda,Java 8,具有如下功能: public void toDo(Req req){ if(req.getSection().equals("A")) { return execA(req); } if(req.getSection().equals("B")) { return execB(req); } if(req.getSection().equals("N")) { return execN(req);

具有如下功能:

public void toDo(Req req){

    if(req.getSection().equals("A")) {
        return execA(req);
    }

    if(req.getSection().equals("B")) {
        return execB(req);
    }

    if(req.getSection().equals("N")) {
        return execN(req);
    }
}

我如何简化它?一般思路是,如何排除函数-Strings-A、B、N的标识类型的if语句。有没有类似于Java8的模式匹配Scala的解决方案

你不能只用一个简单的开关吗

switch (req.getSection()){
    case "A" : execA(req);  break;
    case "B" : execB(req);  break;
    case "N" : execN(req);  break;
    default:  break;
}
此外,它适用于字符串和
int
值,您可以使用
Map

Map<String,Consumer<Req>> handlers;
{
    handlers.put("A", req -> execA(req));
    handlers.put("B", req -> execB(req));
    handlers.put("N", req -> execN(req));
}
Consumer<Req> defaultBehavior=req-> {
    throw new IllegalArgumentException(req.getSection());
};
public void toDo(Req req) {
    handlers.getOrDefault(req.getSection(), defaultBehavior).accept(req);
}
映射处理程序;
{
put(“A”,req->execA(req));
put(“B”,req->execB(req));
put(“N”,req->execN(req));
}
消费者默认行为=请求->{
抛出新的IllegalArgumentException(req.getSection());
};
公共无效待办事项(请求){
getOrDefault(req.getSection(),defaultBehavior).accept(req);
}

除了支持其他键类型外,它还允许在运行时组装映射,例如使用不同的(可能是动态加载的)模块提供的处理程序等。

使用反射和类上的方法数组,可以应用过滤器(如果替换)、映射(返回值)和可选地定义默认值(奥莱尔斯)

如果案例数量很大或是动态的,这种方法可能是好的。但是对于您的特定案例,我认为这太过分了。最好坚持使用切换案例解决方案

public Optional<Object> toDo(Req req) {
    return Stream.of(this.getClass().getMethods())
                 .filter(m -> m.getName().equals("exec" + req.getSection()))
                 .map(this::invokeUnchecked).findFirst();
}

private Object invokeUnchecked(final Method m) {
    try {
        return m.invoke(this);
    } catch (IllegalAccessException| InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}
公共可选toDo(Req){
返回流.of(this.getClass().getMethods())
.filter(m->m.getName().equals(“exec”+req.getSection()))
.map(this::invokeUnchecked).findFirst();
}
私有对象invokeUnchecked(最终方法m){
试一试{
返回m.invoke(this);
}捕获(IllegalAccessException | InvocationTargetException e){
抛出新的运行时异常(e);
}
}

如果不想使用可选的,则必须使用
.findFirst().orElse(()->…)

将代码面向对象,整个方法变为
req.execute();
。除非声明正确的返回类型,否则唯一有效的简化方法是删除整个方法,否则根本无法编译:)非常有趣,而且更好的是,有效地打开了自我修改代码的大门。那是过去的日子。