So, I have multiple txt files, say txt1,txt2,...
and each line has some text between 4 and 22 characters and I have another txt file with similar values, say bigText
. The goal is to check all values that are in bigTxt
that occur somewhere in any of the txt files and output those values (we're guaranteed that if any line of bigTxt
is in any of the txt files, a matching with that line only happens once). The best solution I have so far works, but is slightly inefficient. Basically, it looks like this:
txtFiles.parallelStream().forEach(file->{
List<String> txtList = listOfLines of this txtFile;
streamOfLinesOfBigTxt.forEach(line->{
if(txtList.contains(line)){
System.out.println(line);
//it'd be great if we could just stop this forEach loop here
//but that seems hardish
}
});
});
(Note: I tried breaking out of the forEach using Honza's "bad idea" solution here: Break or return from Java 8 stream forEach? but this must be doing something that's not what I want because it actually made the code usually a bit slower or about the same)
The small problem with this is that even after one file has found a match of one of the lines between the bigTxt
file and the other txt files, other txt files still try to search for checks with that line (even though we've already found one match and that's sufficient). Something that I tried to stop this was first iterating over the bigTxt lines (not in parallel, but going through each txt file was in parallel) and using java's anyMatch
and I was getting a "stream has already been modified or closed" type of error which I understood later was because anyMatch
is terminating. So, after just one call to anyMatch
on one of the lines of one of the txt files, that stream was no longer available for my processing later. I couldn't think of a way to properly use findAny
and I don't think allMatch
is what I want either since not every value from bigTxt
will necessarily be in one of the txt files. Any (parallel) solutions to this (even not strictly including things from Java 8) is welcome. Thank you.