Reputation: 15
private static List<A> compute(Path textFile, String word) {
List<A> results = new ArrayList<A>();
try {
Files.lines(textFile).forEach(line -> {
BreakIterator it = BreakIterator.getWordInstance();
it.setText(line.toString());
int start = it.first();
int end = it.next();
while (end != BreakIterator.DONE) {
String currentWord = line.toString().substring(start, end);
if (Character.isLetterOrDigit(currentWord.charAt(0))) {
if (currentWord.equals(word)) {
results.add(new WordLocation(textFile, line));
break;
}
}
start = end;
end = it.next();
}
});
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
How can I get the line number which the word has been found? I want to use a stream to calculate in Lamdba. Do you have any idea?
Upvotes: 0
Views: 264
Reputation: 5341
public class Try {
public static void main(String[] args) {
Path path = Paths.get("etc/demo.txt");
List<String> result = compute(path, "Test");
result.stream().forEach(s -> System.out.println(s));
}
private static List<String> compute(Path textFilePath, String wordToFind) {
List<String> results = new ArrayList<String>();
// Added position and initialized with 0
int[] position = new int[]{0};
try {
Files.lines(textFilePath).forEach(line -> {
BreakIterator it = BreakIterator.getWordInstance();
it.setText(line.toString());
int start = it.first();
int end = it.next();
// Increment position by 1 for each line
position[0] += 1;
while (end != BreakIterator.DONE) {
String currentWord = line.toString().substring(start, end);
if (Character.isLetterOrDigit(currentWord.charAt(0))) {
if (currentWord.equals(wordToFind)) {
results.add("File Path: " + textFilePath + ", Found Word: " + wordToFind + ", Line: " + position[0]);
break;
}
}
start = end;
end = it.next();
}
});
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
}
demo.txt:
Stream1
Review
Stream
2020-10-10 10:00
Test
0.0
admin HOST Test
Stream2
Review
Output:
Note:
List<String>
.int[] position = new int[]{0};
and position[0] += 1;
for line numbers to be displayed.Test
exists in line number 5
and 7
.Upvotes: 1
Reputation: 555
You can use a LineNumberReader
to get the linenumber. That would look something like this:
private static List<A> compute(Path textFile, String word) {
List<A> results = new ArrayList<A>();
try (final LineNumberReader reader = new LineNumberReader(new FileReader(textFile.toFile()))) {
String line;
while ((line = reader.readLine()) != null) {
BreakIterator it = BreakIterator.getWordInstance();
it.setText(line);
int start = it.first();
int end = it.next();
final int lineNumber = reader.getLineNumber(); // here is your linenumber
while (end != BreakIterator.DONE) {
String currentWord = line.substring(start, end);
if (Character.isLetterOrDigit(currentWord.charAt(0))) {
if (currentWord.equals(word)) {
results.add(new WordLocation(textFile, line));
break;
}
}
start = end;
end = it.next();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
Upvotes: 1