使用Java Stream从文件实例化对象

huangapple go评论132阅读模式
英文:

Instantiating objects from file using Java Stream

问题

parse 方法:

  1. public static Employee parse(String s)
  2. {
  3. String[] empData = s.split(",");
  4. Employee newEmp = new Employee(Integer.parseInt(empData[0]), empData[1], empData[2], BigDecimal.valueOf(Double.parseDouble(empData[3])));
  5. return newEmp;
  6. }

stream 尝试:

  1. // 使用资源管理的方式
  2. try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
  3. List<Employee> employees = stream.map(Employee::parse).collect(Collectors.toList());
  4. } catch (IOException e) {
  5. e.printStackTrace();
  6. }
英文:

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

  1. public static Employee parse(String s)
  2. {
  3. String[] empData = s.split(&quot;,&quot;);
  4. Employee newEmp = new Employee(Integer.parseInt(empData[0]), empData[1], empData[2], BigDecimal.valueOf(Double.parseDouble(empData[3])));
  5. return newEmp;
  6. }

stream attempt

  1. //try with resources
  2. try(Stream&lt;String&gt; stream = Files.lines(Paths.get(fileName))){
  3. stream.forEach(Employee::parse).collect(Collectors.toList());
  4. }
  5. catch(IOException e)
  6. {
  7. e.printStackTrace();
  8. }

答案1

得分: 3

你的想法是正确的,但是你需要使用 map 来获得一个 Employee 流,然后可以进行收集:

  1. List<Employee> employees =
  2. 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 Employees you can then collect:

  1. List&lt;Employee&gt; employees =
  2. Files.lines(Paths.get(fileName)).map(Employee::parse).collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年9月22日 05:54:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64000455.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定