Trying to write a program that sorts a csv file with 5 "fields" using compareTo, and I've got the code working to import the csv file into an arrayList, among a couple of other things. That said, I'm completely stuck on what code I need to actually sort the populated arrayList.
Here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
public class Student implements Comparable<Student>{
public static final String CSV_PATH = "unsortedList.csv";
public static int studentID, mark;
public static String fName, lName, grade;
public static boolean append = true;
public static ArrayList<String> aList = new ArrayList<String>();
public static void main(String[] args) throws IOException {
readAllLinesFromFile(CSV_PATH);
}
public static ArrayList<String> readAllLinesFromFile(String path) throws IOException{
FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = null;
while( (line = bufferedReader.readLine()) != null){
aList.add(line);
}
bufferedReader.close();
System.out.print(aList);
return aList;
}
public static void writeAllLinesToFile(String path, ArrayList<String> aList) throws IOException {
//ArrayList<String> aList = new ArrayList<String>();
FileWriter fileWriter = new FileWriter(path, append);
PrintWriter printWriter = new PrintWriter(fileWriter);
for (String line : aList){
printWriter.printf("%s" + "%n", line);
}
printWriter.close();
}
public Student(int studentID, String fName, String lName, int mark, String grade) {
super();
this.studentID = studentID;
this.fName = fName;
this.lName = lName;
this.mark = mark;
this.grade = grade;
}
public int getStudentID() {
return studentID;
}
public String getfName() {
return fName;
}
public String getlName() {
return lName;
}
public int getMark() {
return mark;
}
public String getGrade() {
return grade;
}
public int compareTo (Student s) {
if (this.mark == s.mark) {
return this.fName.compareTo(s.fName);
} else {
return (s.mark - this.mark) > 0 ? 1 : -1;
}
}
}
And here is an example of the contents of the CSV:
StudentID,FirstName,LastName,FinalMark,FinalGrade
123464,John,Guest,77,P
123456,Dianne,Smith,76,P
122364,Stacey,Hobbs,58,P
123472,Laura,Taylor,67,P
123461,Lazarus,Wonton,42,F
123468,Nola,Emirate,50,P
Any help is greatly appreciated!