英文:
Instantiating objects from file using Java Stream
问题
parse 方法:
public static Employee parse(String s)
{
String[] empData = s.split(",");
Employee newEmp = new Employee(Integer.parseInt(empData[0]), empData[1], empData[2], BigDecimal.valueOf(Double.parseDouble(empData[3])));
return newEmp;
}
stream 尝试:
// 使用资源管理的方式
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
List<Employee> employees = stream.map(Employee::parse).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
英文:
I am in the process of learning about Java 8 Stream API, and there was something I'm trying out that I simply can't get to work. Essentially I have a file containing Strings in the following manner:
0132435,John,Doe,30000.00
Where the first part is an Employee ID, the second is a First name, Third is a Last name, and fourth is yearly salary all separated by commas. I am trying to read this file line by line, pass the entire line to a static method called parse, which will instantiate each Employee, then return that employee, then I want to save all these employees to some kind of list or array so that I can analyze the data. I am trying to do all this with Java stream, but I am having difficulty and don't know why my code does not want to compile. Please keep in mind I am very new at this, Thank you in advance. You can find the code for the stream and parse method below.
parse method
public static Employee parse(String s)
{
String[] empData = s.split(",");
Employee newEmp = new Employee(Integer.parseInt(empData[0]), empData[1], empData[2], BigDecimal.valueOf(Double.parseDouble(empData[3])));
return newEmp;
}
stream attempt
//try with resources
try(Stream<String> stream = Files.lines(Paths.get(fileName))){
stream.forEach(Employee::parse).collect(Collectors.toList());
}
catch(IOException e)
{
e.printStackTrace();
}
答案1
得分: 3
你的想法是正确的,但是你需要使用 map
来获得一个 Employee
流,然后可以进行收集:
List<Employee> employees =
Files.lines(Paths.get(fileName)).map(Employee::parse).collect(Collectors.toList());
英文:
You have the right idea, but you need to use map
to get a stream of Employee
s you can then collect:
List<Employee> employees =
Files.lines(Paths.get(fileName)).map(Employee::parse).collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论