Reputation: 81
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.
Upvotes: 1
Views: 2842
Reputation: 6577
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");
}
}
}
Upvotes: 1
Reputation: 3507
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
}
Upvotes: 1