【问题标题】:Reduce number of conditional operators减少条件运算符的数量
【发布时间】:2017-01-19 16:21:01
【问题描述】:

我有一个字符串数组列表。让我们说

private final List<String> fruits = new ArrayList<String>();

现在我必须将传入的行与数组列表中的项目进行比较

while ((line = in.readLine()) != null) {
    if (!(line.equals(fruits.get(0)) || line.contains(fruits.get(1)) ||
        line.contains(fruits.get(2)) || line.contains(fruits.get(3)) ||
        line.contains(fruits.get(4)) || line.contains(fruits.get(5)) ||
        line.contains(fruits.get(6)) || line.equals(fruits.get(7)    ||  line.equals(fruits.get(8)))) {
          //                   "DO SOMETHING"
     }
}

在某些情况下,我必须完全匹配字符串,而在某些情况下只使用 contains。但最后我的 if 子句中的条件不应超过 3 个。

【问题讨论】:

  • 你考虑过使用循环吗?
  • 构建正则表达式。
  • 使用 if 语句编写方法,但不使用条件运算符。
  • 可以使用StringUtils.containsAny(CharSequence, CharSequence...)检查字符串是否是数组中任何字符串的子集。真正的问题是只检查一些是否相等。唯一的选择是遍历函数并知道哪些元素必须相等。
  • 我很确定您在这里遇到了编译错误:line.equals(fruits.get(7) || line.equals(fruits.get(8)))

标签: java


【解决方案1】:

由于您想对列表中的每个水果使用 equals() 或 contains() 并且您的水果一直在增长,因此请考虑将您的列表转换为地图,在其中按水果存储所需的方法。

private enum Method {
    CONTAINS,
    EQUALS;
}

@Test
public void testFruits() throws IOException {
    Map<String, Method> methodByFruit = new HashMap<>();
    methodByFruit.put("apple", Method.CONTAINS);
    methodByFruit.put("pear", Method.CONTAINS);
    methodByFruit.put("grenade apple", Method.CONTAINS);
    methodByFruit.put("banana", Method.EQUALS);
    methodByFruit.put("kiwi", Method.EQUALS);

    BufferedReader in = new BufferedReader(new StringReader("kiwi2"));

    String line;
    while ((line = in.readLine()) != null) {
        boolean success = false;
        for (Entry<String, Method> entry : methodByFruit.entrySet()) {
            String fruit = entry.getKey();
            Method method = entry.getValue();
            if (method == Method.EQUALS) {
                success = line.equals(fruit);
            } else {
                success = line.contains(fruit);
            }
            if (success) {
                break;
            }
        }
        if (!success) {
            System.out.println("DO SOMETHING");
        }
    }
}

【讨论】:

    【解决方案2】:

    您的要求不清楚。相等性检查是否专门针对索引 78 仅或什么。但无论如何,这是我的建议。你可以做一个简单的方法来检查line是否包含list的子集

    public boolean isFound(List<String> f, String l){
        for(int i=0;i<f.size();i++){
            if(l.contains(f.get(i)){
                return true;
            }
        }
        return false;
    }
    

    然后你可以这样检查:

    if(isFound(fruits, line) || fruits.contains(line)){
        //Do Something
    }
    

    【讨论】:

    • equals 仅用于索引 0,7,8
    猜你喜欢
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多