简体   繁体   中英

Reduce number of conditional operators

I have an String arraylist. Lets say

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

Now I have to compare an incoming line against the items in the arraylist

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"
     }
}

I have to match the string exactly for some cases and just use contains for some cases. But at last I should not have more than 3 conditions in my if clause.

Your requirement is not clear. Whether the equality check is specifically for index 7 or 8 only or what. But anyway here is my suggestion. you can make a simple method to check if line contains subset from the 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;
}

Then you can check it like this:

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

Since you want to use either equals() or contains() on each fruit in the list and your fruits are ever growing, consider turning your list into a map, where you store the desired method by fruit.

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");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM