Any implementation of Map <K1, K2, V>, that is, two keys?

I need a card with two keys, for example

Map2<String /*ssn*/, String /*empId*/, Employee> _employees; 

So i can

 _employees.put(e.ssn(), e.empId(), e) 

And later

 _employees.get1(someSsn); _employees.get2(someImpId); 

Or even

 _employees.remove1(someImpId); 

I'm not sure why I want to stop at two, why not more, perhaps because in this case I need now :-) But the type must process a fixed number of keys in order to be type safe - type parameters cannot be vararg :-)

Appreciate any pointers or tips on why this is a bad idea.

+6
java generics maps
source share
3 answers

My first thought was: the easiest way to do this, I think, would be two cards.

 Map< String, Map< String,Employee> > _employees; 

But from what it looks like, you just want to find an employee by SSN or ID. What then can stop you from creating two cards or, in the worst case, a class containing two cards?

As a clarification, are you looking for a composite key that serves uniquely identified by a combination of their SSN and ID, but not one of them in itself, or are you looking for two different ways to refer to an employee?

+4
source share

I assume that the main key will be empId , so I would build a Map using this key, i.e. empId ---> Employee . All other unique attributes (for example, ssn ) will be considered secondary and will use a separate Map as a lookup table for empId (for example, ssn ---> empId ).

This implementation makes adding / removing employees easier since you only need to change one Map , i.e. empId ---> Employee ; another Map can only be rebuilt if necessary.

+4
source share

The Spiffy Framework seems to provide exactly what you are looking for. From Javadocs:

A two-dimensional hashmap is the HashMap, which allows you to refer to values ​​through two keys, not one

The corresponding class is TwoDHashMap . It also provides ThreeDHashMap .

+2
source share

All Articles