Efficient data structure with two keys

I have an Android app in which I use HashMap to store container objects. While the application is running, data is always available.

However, in about half the cases, the link is used not in Key on the map, but in another variable from the object, so I finish the cycle over the structure again and again.

Is there an efficient way to index a datastructure on two keys in Java?

+4
source share
4 answers

Why not two cards with different keys, but what both refer to the same values?

+5
source

Manage two cards where two sets of keys are mapped to the same basic set of objects. Wrap them in a class that has methods similar to a normal map, but internally searches for both keys and synchronizes additions and deletions.

This is effective because the manipulation (in the worst case) is linearly proportional to the management of one card.

+1
source

You can use one card with two keys:

 Map<Object, Person> personMap = new HashMap<Object, Person>() Person person = ... personMap.put(person.getName(), person) personMap.put(person.getSSN(), person) 

Then you can get the key. This, of course, assumes that there are no conflicts in your key usage. If your two keys have different class types, this is safe. If your keys are of the same type ( String example), you may not want to use two card solutions.

Follow-up actions: This approach does suffer from type safety loss, but it only affects put(K, V) and putAll(Map<? extends K, ? extends V>) , since get(Object) and containsKey(Object) always accept an object.

So, with this restriction, I would wrap this single card or move with two card solutions (also wrapped).

+1
source

I would create a key object that combines two variables.

+1
source

Source: https://habr.com/ru/post/1396534/


All Articles