简体   繁体   中英

Can I use map to set the value for other objects in java8 stream?

Am I allowed to write code this way?

Can I use setter inside map method to set the values to other objects using stream?

try (BufferedReader bufferedReader = new BufferedReader(new FileReader(csvPath))) {
        List<Employee> employees = bufferedReader
                .lines()
                .skip(1)
                .map(l -> {
                    String[] lines = l.split(",");
                    Employee employee = new Employee();
                    employee.setEmployeeId(Long.parseLong(lines[0]));
                    employee.setFullName(lines[1] + " " + lines[2] + " " + lines[3]);
                    employee.setGender(lines[4]);
                    employee.setEmail(lines[5]);
                    employee.setSalary(Double.parseDouble(lines[6]));
                    employee.setState((lines[7]));
                    return employee;
        }).collect(Collectors.toList());

Yes, you can. Although I wouldn't recommend that.

Just extract that logic into a separate method instead:

Employee parseEmployee(String line) {
    String[] columns = line.split(",");
    Employee employee = new Employee();
    employee.setEmployeeId(Long.parseLong(columns[0]));
    employee.setFullName(columns[1] + " " + columns[2] + " " + columns[3]);
    employee.setGender(columns[4]);
    employee.setEmail(columns[5]);
    employee.setSalary(Double.parseDouble(columns[6]));
    employee.setState((columns[7]));
    return employee;
}

then just pass the method reference into map :

List<Employee> employees = bufferedReader.lines()
                                         .skip(1)
                                         .map(this::parseEmployee)
                                         .collect(toList());

This will make your code much more readable and easier to maintain.

I will recommend to move the logic into Employee constructor

public Employee(String[] lines) {
  this.employeeId = Long.parseLong(lines[0]);
  this.fullName = lines[1] + " " + lines[2] + " " + lines[3];
  this.gender = lines[4];
  this.email = lines[5];
  this.salary = Double.parseDouble(lines[6]);
  this.state = lines[7];

 }

And then just use the constructor for creating Employee object

List<Employee> employees = bufferedReader
            .lines()
            .skip(1)
            .map(l-> l.split(","))
            .map(Employee::new)
            .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM