Я пытаюсь сортировать текстовый файл, который разделен вкладками и пытается сортировать по третьему полю, className. Я собираюсь отобразить его в таблице. Я написал следующую часть, но она не сортируется правильно. Любые идеи относительно того, где я ошибаюсь?Сравните using Collections.sort
public void sortFile(){
BufferedReader reader = null;
BufferedWriter writer = null;
//Create an ArrayList object to hold the lines of input file
ArrayList<String> lines = new ArrayList<>();
try{
//Creating BufferedReader object to read the input file
reader = new BufferedReader(new FileReader("pupilInfo.txt"));
//Reading all the lines of input file one by one and adding them into ArrayList
String currentLine = reader.readLine();
while (currentLine != null){
lines.add(currentLine);
currentLine = reader.readLine();
}
Collections.sort(lines, (String s1, String s2) -> {
s1 = lines.get(0);
s2 = lines.get(1);
String [] line1 = s1.split("\t");
String [] line2 = s2.split("\t");
String classNameLine1 = line1[2];
String classNameLine2 = line2[2];
System.out.println("classname1=" + classNameLine1);
System.out.println("classname2=" + classNameLine2);
int sComp = classNameLine1.compareTo(classNameLine2);
return sComp;
});
//Creating BufferedWriter object to write into output temp file
writer = new BufferedWriter(new FileWriter("pupilSortTemp.txt"));
//Writing sorted lines into output file
for (String line : lines){
writer.write(line);
writer.newLine();
}
}catch (IOException e){
}
finally{
//Closing the resources
try{
if (reader != null){
reader.close();
}
if(writer != null){
writer.close();
}
}catch (IOException e){
}
}
}
's1 = lines.get (0); s2 = lines.get (1); '- что ты делаешь? – user2357112
Если вы удалите две строки, идентифицированные @ user2357112, это будет хорошим началом для устранения вашей проблемы. –
Компаратор, который вы передаете в 'Collections.sort', уже передается в строках, которые нужно сравнивать (из вашего ArrayList), поэтому вам не нужно устанавливать их вручную. Кроме того, вы фактически перезаписываете правильные значения, переданные компаратору. –