Home > Mobile >  How to check two lists with different Types but having a Common property
How to check two lists with different Types but having a Common property

Time:10-26

Assume I have two lists with different domain objects of different types: Customer and Employee.

And these objects have the common companyId property.

Customer class:

public static class Customer {
    private Long companyId;
    private String companyName;
}

Employee class:

public static class Employee {
    private Long companyId;
    private String companyName;
}

Employee has this property in common companyId assigned, but the companyName is missing.

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

First I tried with two nested for-loops, but I think it is not very performance-vice, if I have over 1000 elements.

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

Maybe store the data from 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