Search code examples
javacollections

Detect duplicate email id in arraylist containg multiple employee objects


Suppose I have a arraylist , I am dynamically adding multiple employee objects to the arraylist. Employee object have field like Id, name, email . My requirement is when I am adding a employee object to arraylist. Suppose that object having a email which is already there of another object added to arraylist. Then it should not allow to add current object to the arraylist or show some error message.Is there any methods available in Collection module to achieve this thing in shortest possible way..


Solution

  • // Use LinkedHashMap to keep insertion order
    Map<String, Employee> employees = new LinkedHashMap<>();
    
    // v1: add new employee with unique email
    employees.putIfAbsent(employee.getEmail(), employee);
    
    // v2: add new employee and show message for duplication email
    if(employees.containsKey(employee.getEmail()))
        System.out.println("Email " + employee.getEmail() + " duplication");
    else
        employees.put(employee.getEmail(), employee);
    
    // get all employees in order they were added
    List<Employee> res = new ArrayList<>(employees.values());