It depends on what stringArray . If this is a Collection , then great. If it is a true array, you should make it a Collection . The Collection interface has a contains() method that determines whether a given Object in a Collection .
An easy way to turn an array into a Collection :
String tokens[] = { ... } List<String> list = Arrays.asList(tokens);
The problem with List is that the search for roads (technically linear or O(n) ). It is best to use a Set that is disordered but has an almost constant ( O(1) ) search. You can build one like this:
From Collection :
Set<String> set = new HashSet<String>(stringList);
From the array:
Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
and then set.contains(line) will be a cheap operation.
Edit: Well, I think your question is not clear. You want to see if a string contains any of the words in the array. Then you want 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 a pretty crude test, which is used surprisingly open and tends to produce annoying false positives on words like "scrap." For a more complex solution, you probably have to use a regular expression and look for word boundaries:
Pattern p = Pattern.compile("(?<=\\b)" + word + "(?=\b)"); Matcher m = p.matcher(line); if (m.find() {
You probably want to do this more efficiently (for example, not compiling the template with each line), but here is the main tool to use.
source share