I want to search a list of strings from the file and get the line number. I am looking for an efficient way to do it. I don’t want to search one string at a time and open and close file.
Advertisement
Answer
Store the line numbers where each String appears in the file using a HashMap<String, List<Integer>>.
This will allow you to find all lines in which a given String appears in a few microseconds.
Here’s one way, if each line is one String:
Map<String, List<Integer>> index = new HashMap<>();
LineNumberReader lines = new LineNumberReader(new FileReader("myfile.txt"));
for (String line = lines.readLine(); line != null; line = lines.readLine()){
index.computeIfAbsent(line, x -> new ArrayList<>()).add(lines.getLineNumber());
}
If each line is multiple Strings, change this line
index.computeIfAbsent(line, x -> new ArrayList<>()).add(lines.getLineNumber());
to
Arrays.stream(line.split(" ")).forEach(word ->
index.computeIfAbsent(word, x -> new ArrayList<>())
.add(lines.getLineNumber())
);