Dear fellow developers I am doing a java program which compare two text files line by line, first text file has 99,000 lines and the other file has 1,15,000 lines. I want to read the files and compare in such a way so that if any line matches between the first file and the second file it should print the match.
I have written the code but it is taking almost 10 mins to complete, as it is printing due to the for
loop. How can it be made fast, efficient and efficient in terms of memory allocation? How can it be optimized for performance? Please guide me.
public class Main {
static final String file1 = "file1.txt";
static final String file2 = "file2.txt";
static BufferedReader b1 = null;
static BufferedReader b2 = null;
static List<String> list_file1 = null;
static List<String> list_file2 = null;
public static void main(String[] args) {
list_file1 = new ArrayList<String>();
list_file2 = new ArrayList<String>();
String lineText = null;
try {
b1 = new BufferedReader(new FileReader(file1));
while ((lineText = b1.readLine()) != null) {
list_file1.add(lineText);
}
b2 = new BufferedReader(new FileReader(file2));
while ((lineText = b2.readLine()) != null) {
list_file2.add(lineText);
}
compareFile(list_file1,list_file2);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void compareFile(List<String> list_file1, List<String> list_file2) {
for(String content1:list_file1){
for(String content2:list_file2){
if(content1.equals(content2)){
System.out.println("Match Found:-"+content1);
}
}
}
}
}
java [your.class] > output.txt
? \$\endgroup\$1,15,000 lines
shouldn't there be three digits in every group ticked off? \$\endgroup\$