简体   繁体   English

按一个字段对csv文件进行排序

[英]Sorting csv file by one field

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. 试图编写一个使用compareTo对具有5个“字段”的csv文件进行排序的程序,除其他外,我已经获得了将csv文件导入到arrayList中的代码。 That said, I'm completely stuck on what code I need to actually sort the populated arrayList. 就是说,我完全停留在实际对填充的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: 这是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! 任何帮助是极大的赞赏!

Take a look at this post: How to sort an ArrayList in Java 看一下这篇文章: 如何在Java中对ArrayList进行排序

The way I see it, you should override the compare function, and then call the sort function on your arraylist. 我的看法是,您应该重写compare函数,然后在arraylist上调用sort函数。

EDIT: tried it for myself. 编辑:自己尝试过。

import java.io.BufferedReader;
import java.io.FileReader; 
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Main {

public static final String CSV_PATH = "unsortedList.csv";
public static boolean append = true;
public static ArrayList<String> aList = new ArrayList<String>();

public static void main(String[] args) throws IOException {

    readAllLinesFromFile(CSV_PATH);
    System.out.println("Unsorted:\n");
    for(String aStudentString: aList){
        System.out.println(aStudentString +"\n");
    }

    ArrayList<Student> students = convertToStudents(aList);
    System.out.println("SORTED:\n");
    for(Student student : students){
        System.out.println(student.toString());
    }
}

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();

    return aList;

}

public static ArrayList<Student> convertToStudents(ArrayList<String> studentsStrings) {
    ArrayList<Student> students = new ArrayList<>();
    studentsStrings.remove(0);
    for(String studentString : studentsStrings) {
        String[] parts = studentString.split(",");
        int studentID = Integer.valueOf(parts[0]);
        String fName = parts[1];
        String lName = parts[2];
        int mark = Integer.valueOf(parts[3]);
        String grade = parts[4];
        students.add(new Student(studentID, fName, lName, mark, grade));
    }

    Collections.sort(students, new Comparator<Student>() {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.compareTo(o2);
        } 
    });
    return students;
}
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();
}
}

And the student class: 和学生班:

public class Student implements Comparable<Student>{

public int studentID, mark;
public String fName, lName, grade;

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;
}

@Override
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;
    }
}

@Override
public String toString() {
    return "Student{" + "studentID=" + studentID + ", mark=" + mark + ", fName=" + fName + ", lName=" + lName + ", grade=" + grade + '}';
}

}

You need to implement the Comparable interface for your Student . 您需要为Student实现Comparable接口。 According to javadoc compareTo needs to return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. 根据javadoc, compareTo需要返回负整数,零或正整数,因为此对象小于,等于或大于指定的对象。 So you don't have to return either -1 or 0 or 1 : 因此,您不必返回-101

class Student implements Comparable<Student> {

    private int studentID;
    private String fName;
    private String lName;
    private int mark;
    private String grade;

    public Student(int studentID, String fName, String lName, int mark, String grade) {
        this.studentID = studentID;
        this.fName = fName;
        this.lName = lName;
        this.mark = mark;
        this.grade = grade;
    }

    @Override
    public int compareTo(Student o) {
        return o.mark - this.mark; // DESC
    }

    @Override
    public String toString() {
        return studentID + "," + fName + "," + lName + "," + mark + "," + grade;
    }
}

And your code eventually might look like this: 您的代码最终可能看起来像这样:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) throws IOException {
        File input = new File("mycvs.cvs");
        File output = new File("sorted.cvs");
        Main m = new Main();
        List<Student> students = m.sort(input, 2);
        m.write(output, students);
    }

    private void write(File output, List<Student> students) throws IOException {
        Path path = Paths.get(output.toURI());
        List<String> listStudents = new ArrayList<>(students.size());
        for (Student s: students) {
            listStudents.add(s.toString());
        }
        Files.write(path, listStudents);
    }

    private List<Student> sort(File f, int columnToSort) throws IOException {
        Path path = Paths.get(f.toURI());
        List<String> allLines = Files.readAllLines(path);
        List<Student> students = new ArrayList<>(allLines.size());
        for (int i = 1; i < allLines.size(); i++) {
            String line = allLines.get(i);
            String[] columns = line.split(",");
            Student s = new Student(Integer.parseInt(columns[0]), columns[1], columns[2], Integer.parseInt(columns[3]), columns[4]);
            students.add(s);
        }
        Collections.sort(students);
        return students;
    }
}

class Student implements Comparable<Student> {

    private int studentID;
    private String fName;
    private String lName;
    private int mark;
    private String grade;

    public Student(int studentID, String fName, String lName, int mark, String grade) {
        this.studentID = studentID;
        this.fName = fName;
        this.lName = lName;
        this.mark = mark;
        this.grade = grade;
    }

    @Override
    public int compareTo(Student o) {
        return o.mark - this.mark; // DESC
    }

    @Override
    public String toString() {
        return studentID + "," + fName + "," + lName + "," + mark + "," + grade;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM