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

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

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(&quot;,&quot;); 
		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&lt;String&gt; 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 Employees you can then collect:

List&lt;Employee&gt; employees = 
    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:

确定