[英]Reduce number of conditional operators
I have an String arraylist. 我有一个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 现在我必须将输入行与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.
但是最后,我的if子句中不应有3个以上的条件。
Your requirement is not clear. 您的要求不清楚。 Whether the equality check is specifically for index
7
or 8
only or what. 相等性检查是否仅专门针对索引
7
或8
或什么。 But anyway here is my suggestion. 但是无论如何,这是我的建议。 you can make a simple method to check if
line
contains subset from the list
您可以创建一种简单的方法来检查
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;
}
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. 由于您要在列表中的每个水果上使用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");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.