Home  >  Article  >  Java  >  How to Create a Map with Multiple Keys for Value Access?

How to Create a Map with Multiple Keys for Value Access?

DDD
DDDOriginal
2024-11-05 17:16:021002browse

How to Create a Map with Multiple Keys for Value Access?

Implementing a Map with Multiple Keys

Question:

How can I create a data structure that behaves like a Map but uses multiple (differently-typed) keys to access its values? The keys are guaranteed to be unique. I need methods like getByKey1, getByKey2, containsKey1, and containsKey2.

Answer:

One approach is to use two internal Maps:

  • Map
  • Map

This method allows you to search values using either key because each key has its own Map.

Additional Notes:

  • The suggestion of using a tuple or pair as a key for Java's Map would not work in this case because you need to be able to search values by only one of the two specified keys.

Example Code:

<code class="java">import java.util.HashMap;
import java.util.Map;

class MyMap<K1, K2, V> {
    private Map<K1, V> map1;
    private Map<K2, V> map2;

    public MyMap() {
        map1 = new HashMap<>();
        map2 = new HashMap<>();
    }

    public V getByKey1(K1 key) {
        return map1.get(key);
    }

    public V getByKey2(K2 key) {
        return map2.get(key);
    }

    public boolean containsKey1(K1 key) {
        return map1.containsKey(key);
    }

    public boolean containsKey2(K2 key) {
        return map2.containsKey(key);
    }

    public void put(K1 key1, K2 key2, V value) {
        map1.put(key1, value);
        map2.put(key2, value);
    }
}</code>

The above is the detailed content of How to Create a Map with Multiple Keys for Value Access?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn