It depends on what stringArray
is. If it's a Collection
then fine. If it's a true array, you should make it a Collection
. The Collection
interface has a method called contains()
that will determine if a given Object
is in the Collection
.
Simple way to turn an array into a Collection
:
String tokens[] = { ... }
List<String> list = Arrays.asList(tokens);
The problem with a List
is that lookup is expensive (technically linear or O(n)
). A better bet is to use a Set
, which is unordered but has near-constant (O(1)
) lookup. You can construct one like this:
From a Collection
:
Set<String> set = new HashSet<String>(stringList);
From an array:
Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
and then set.contains(line)
will be a cheap operation.
Edit: Ok, I think your question wasn't clear. You want to see if the line contains any of the words in the array. What you want then is something like this:
BufferedReader in = null;
Set<String> words = ... // construct this as per above
try {
in = ...
while ((String line = in.readLine()) != null) {
for (String word : words) {
if (line.contains(word)) [
// do whatever
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) { try { in.close(); } catch (Exception e) { } }
}
This is quite a crude check, which is used surprisingly open and tends to give annoying false positives on words like "scrap". For a more sophisticated solution you probably have to use regular expression and look for word boundaries:
Pattern p = Pattern.compile("(?<=\\b)" + word + "(?=\b)");
Matcher m = p.matcher(line);
if (m.find() {
// word found
}
You will probably want to do this more efficiently (like not compiling the pattern with every line) but that's the basic tool to use.