Home > OS >  How to check two lists with different objects but common value
How to check two lists with different objects but common value

Time:10-25

Assume I have two lists with different objects. The objects have the id in common.

The two different objects are Customer and Employee.

Customer has this properties:

private Long companyId;
private String companyName;

Employee has this property in common private Long companyId What is missing is the companyName

I have two lists:

List<Customer> customerList;
List<Employee> employeeList;

What I want to do is to set the companyName for each Employee where the companyId from Employee == companyId of Customer

What is the best way with respect to performance to achieve this?

First I tried with a double loop but I think it is not good for the performance if I have over 1000 data and so on.

Maybe save customerList as a HashMap and then for each Employee do get(companyId) or so?

CodePudding user response:

You were thinking in the right direction. Generating a Map which associates companyId of each customer with a companyName would be a more performant approach than using a nested for-loop.

When we have a Map, the only thing left is iterate through the list of Employee and if its companyId exists in the Map replace the companyName with the one that is stored in the Map.

public static void setCompanyNames(List<Customer> customerList,
                                   List<Employee> employeeList) {
    
    Map<Long, String> companyNameByCustomerId = customerList.stream()
        .collect(Collectors.toMap(
            Customer::getCompanyId,   // generating Keys
            Customer::getCompanyName, // generating Values
            (left, right) -> left     // resolving duplicates (this argument is need if there could be several customers with the same companyId)
        )); 
    
    for (Employee employee: employeeList) {
        Long id = employee.getCompanyId();
        if (companyNameByCustomerId.containsKey(id)) {
            employee.setCompanyName(companyNameByCustomerId.get(id));
        }
    }
}
  • Related