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

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

DDD
Release: 2024-11-05 17:16:02
Original
1103 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template