I am making an application which involves reading text files (.txt) and one of the requirements is to keep a N (where N is specified by the user) number of longest lines in the file while maintaining the order in which they appear within the file.
So, for example if a file has 10 lines and N = 4, then the 4 longest lines in the file will be kept while all other lines will be removed. This is to be done while maintaining the order in which they appear within the file.
I'm using a LinkedHashMap to store the contents of the line as the Key and length of the line as the value.
LinkedHashMap<String, Integer> linesInFile = new LinkedHashMap<String, Integer>();
String line = "";
String newFileContent = "";
try {
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
while ((line = br.readLine()) != null) {
linesInFile.put(line, line.length());
}
br.close();
List<Entry<String, Integer>> lineList = new ArrayList<Entry<String, Integer>>(linesInFile.entrySet());
List<Entry<String, Integer>> lineOrder = new ArrayList<Entry<String, Integer>>(linesInFile.entrySet());
Collections.sort(lineList, (e1, e2) -> (e2.getValue() - e1.getValue()));
int i = 0;
while (N > 0) {
newFileContent += lineList.get(i).getKey() + System.lineSeparator();
i++;
N--;
}
} catch (Exception e) {
// do something
}
The problem with the above is it doesn't preserve ordering of the lines in the file. How do I preserve the order in which the lines appear?
For example if I have the following file
Log: 123 abc
Error: 456123123 123 xyz
Log: 456 cde
Log: 1231 cde
Error: 123123 ab c
Error: 456123 123 xyz
Log: 123 cde
Error: 456 123 qrz
Error: 123 123 xyz
Log: 456 cde
Log: 456 cde
If I were to keep the 4 longest lines in the file, the file after changes would be
Error: 456123123 123 xyz
Error: 123123 ab c
Error: 456123 123 xyz
Error: 456 123 qrz