Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi Key Hashmap

Tags:

java

Recently I had an interview to save the huge count of employee details in DS.

I gave the solution as Hashmap with emp Id as key.

The follow up question was if the user wants to search based on name how to implement it. I suggested to use emp name as key and save all the employees with same name as Arraylist.

The next follow up question was tricky, need to create ONE map where user can search based on emp Id or emp name. How to implement this in map?

Implement it in memory efficient way.

like image 762
Lathy Avatar asked Oct 20 '22 01:10

Lathy


2 Answers

This is a dirty solution (yes--very dirty, never do it on production!), but it will work if keys are of different types and one is not subtype of another (e.g. long and String). Put every employee by both keys, and get by provided key, either id or name:

Map<?, List<Employee>> map = new HashMap<>();

public void putEmployee(Employee e) {
    map.put(e.id, Arrays.asList(e));    // put by id
    if (!map.containsKey(e.name)) {
        map.put(e.name, new ArrayList<>());
    }
    map.get(e.name).add(e);             // put by name
}

public Employee getById(long id) {
    return map.containsKey(id) ? map.get(id).get(0) : null;
}

public List<Employee> getByName(String name) {
    return map.containsKey(name) ? map.get(name) : Collections.emptyList();
}

In production code, I'd use two separate maps or custom dictionary class.

like image 169
Alex Salauyou Avatar answered Nov 02 '22 12:11

Alex Salauyou


I have come up with a solution. Please post your suggestions.

Step 1: Form the hashmap with emp id as key and emp object as value.

Step 2: For the same name create a list of emp id who matches the name Ex: name = 'XYZ' id={101,102,103,...}

Step 3: Insert this name as key and arraylist as value to the same map

Here we are not storing complete employee detail twice. Just trying to maintain a relationship between name and id. So comparatively it could be memory efficient.

like image 25
Lathy Avatar answered Nov 02 '22 12:11

Lathy