Reputation: 3
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);
}
Upvotes: 0
Views: 150
Reputation: 1561
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);
}
Upvotes: 2