简体   繁体   中英

Read data from file using Java 8?

I am trying to convert this piece of code to Java 8 with streams. I am reading from a file which has 3 or more columns. This depends on how many grades does a student have. The first Column contains the name of the student. The second one contains the gender of the student. The next columns the grades. The delimiter is a comma. I want to have the values in the variables the same way as I have down below.

@Override
    public List<Student> processFile(String filename) {
        ArrayList<Student> students = new ArrayList<>();
        try{
            BufferedReader reader =  new BufferedReader(new FileReader( new File(filename)));
            String line = reader.readLine();
            while(line != null) {
                String[] splitline = line.split(",");
                String name = splitline[0];
                String gender = splitline[1];
                int[] grades = new int[splitline.length -2];

                for(int i = 2; i < splitline.length; i++){
                    grades[i - 2] = Integer.parseInt(splitline[i]);
                }

                students.add(new Student(name, gender, grades));
                line=reader.readLine();
            }
        } catch (Exception e){
            e.printStackTrace();
        }

        students.sort(Comparator.comparing(Student::getName));
        return students;
    }

After this I want to get the Students with tens, which I do the following way:

private void printStudentsWithTens(List<Student> students) {
        StringBuilder res = new StringBuilder("Name of Students with tens: ");
       res.append(students.stream()
                .filter(student -> Arrays.stream(student.getGrades()).anyMatch(g -> g == 10))
                .map(student -> student.getName().split(" ")[0])
                .collect(Collectors.joining(", ")));

        System.out.println(res);
    }

Something like this:

try(BufferedReader r = new BufferedReader(new FileReader(new File(filename)))) {
    return r.lines()
        .map(line -> line.split(","))
        .map(this::loadStudent)
        .sorted(Comparator.comparing(Student::getName))
        .collect(toList());
}

...

private static Student loadStudent(String[] splitline) {
    // TODO - the grades code you already have
    return new Student(splitline[0], splitline[1], grades);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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