如何替换多个if-else语句以优化代码? [英] How to replace multiple if-else statements to optimize code?

查看:306
本文介绍了如何替换多个if-else语句以优化代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有什么方法可以优化此代码.

I want to know if there is any way i could optimize this code.

String[] array;
for(String s:array){
   if(s.contains("one"))
       //call first function
   else if(s.contains("two"))
      //call second function
   ...and so on
}

字符串基本上是我正在从文件中读取的行,因此可以有很多行,而且我必须在这些行中查找特定的关键字并调用相应的函数.

The string is basically lines I am reading from a file.So there can be many number of lines.And I have to look for specific keywords in those lines and call the corresponding function.

推荐答案

这不会阻止您的代码执行许多String#contains调用,但是,它将避免if/else链接..

This wont stop you code from doing many String#contains calls, however, it will avoid the if/else chaining..

您可以创建一个按键功能映射,然后遍历该映射的条目以查找要调用的方法.

You can create a key-function map and then iterate over the entries of this map to find which method to call.

public void one() {...}
public void two() {...}
private final Map<String, Runnable> lookup = new HashMap<String, Runnable>() {{
    put("one", this::one);
    put("two", this::two);
}};

然后您可以遍历条目集:

You can then iterate over the entry-set:

for(final String s : array) {
    for(final Map.Entry<String, Runnable> entry : lookup) {
        if (s.contains(entry.getKey())) {
            entry.getValue().run();
            break;
        }
    }
}

这篇关于如何替换多个if-else语句以优化代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆