From a REST service, I will get the response as List of Employees. Which may contains multiple addresses for same employee as defined below.
[Employee{empId=1, name='Emp1', address='Emp1 Address1'},
Employee{empId=1, name='Emp1', address='Emp1 Address 2'},
Employee{empId=2, name='Emp2', address='Emp2 Address 1'}]
By creating an another list i.e List<EmployeeNormalized >, the above response needs to be processed in a normalized way, as defined below.
[EmployeeNormalized{empId=1, name='Emp1',
addresses=[Emp1 Address1, Emp1 Address 2]},
EmployeeNormalized{empId=2, name='Emp2', addresses=[Emp2 Address 1]}]
Code snippet:
class Employee {
private int empId;
private String name;
private String address;
// 50 other properties
public Employee(int empId, String name, String address) {
this.empId = empId;
this.name = name;
this.address = address;
}
// Setters and Getters
}
class EmployeeNormalized {
private int empId;
private String name;
private List<String> addresses;
// 50 other properties
public EmployeeNormalized(int empId, String name, List<String> address) {
this.empId = empId;
this.name = name;
this.addresses = address;
}
// Setters and Getters
}
List<EmployeeNormalized > must contain unique employee objects and List<String> in the EmployeeNormalized class should accommodate all the addresses for that employee.
EDIT: Employee class has around 50 properties.
How do I create this normalized form of list?
Stream solution:
Quite complex, need to call distinct to get rid of duplicating instances.
I would go for simple loop:
Basically both solutions use employee id as unique identifer, and map instances to id. If id is met for the first time, create instance and add address, if there is already instances for this id, get the instance and add address.
Edit: Since
computeIfAbsentis undesireable due to many properties, you can add no argument constructor and transfer property values with setters. The best option would be to use mapping library, then you could do it withcomputeIfAbsentas well.