簡體   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