繁体   English   中英

使用 Java 8 从文件中读取数据?

[英]Read data from file using Java 8?

我正在尝试将这段代码转换为带有流的 Java 8 。 我正在从具有 3 列或更多列的文件中读取。 这取决于学生的成绩。 第一列包含学生的姓名。 第二个包含学生的性别。 接下来的列是成绩。 分隔符是逗号。 我希望变量中的值与下面的相同。

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

在此之后,我想获得几十个学生,我这样做的方式如下:

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

像这样的东西:

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

暂无
暂无

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

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