DrakeWalker
DrakeWalker

Reputation: 57

Semi-Unique Nested Java Map?

I've seen a few questions about this, but not one that actually pertains to what I am trying to do.

Example of what I need:

I have a key(String), key(String), value(Integer):

"Salt", "Salt", 0

"Salt", "Pepper", 1

I want to be able to call:

map.get("Salt"), and have it:
  A: Return "Salt" and "Pepper"
map.get("Salt").get("Salt")) and have it:
  A. Return 0
map.get("Salt").get("Pepper")) and have it:
  A. Return 1

I've tried nested Linked/hashmaps, but adding the second salt value overrides the first...and I can't figure out how to have it so the second key does not override the first one.

Upvotes: 0

Views: 316

Answers (2)

cse
cse

Reputation: 4104

You can achieve this with following class. See the working code here:

class CustomMap<K1, K2, V>
{
    private HashMap<K1, HashMap<K2, V>> map;
    public CustomMap()
    {
        map = new HashMap<>();
    }

    public void put(K1 key1, K2 key2, V value) {
        HashMap<K2, V> lMap = map.get(key1);
        if(lMap != null) lMap.put(key2, value);
        else
        {
            lMap = new HashMap<>();
            lMap.put(key2, value);
            map.put(key1, lMap);
        }

    }

    public Set<K2> get(K1 key) {
        HashMap<K2, V> lMap =  map.get(key);
        return lMap == null ? null : lMap.keySet();
    }

    public V get(K1 key, K2 key2) {
        HashMap<K2, V> lMap =  map.get(key);
        if(lMap == null) return null ;
        return lMap.get(key2);
    }
}

Following is sample code for use:

    CustomMap<String, String, Integer> map = new CustomMap<>();
    map.put("Salt", "Salt", 0);
    map.put("Salt", "Pepper", 1);

    System.out.println(map.get("Salt"));
    System.out.println(map.get("Salt", "Pepper")); 

Output:

[Salt, Pepper]
1

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140329

You can use a Map<String, Map<String, Integer>>:

Map<String, Map<String. Integer>> map =
    new HashMap<>();

Add values like this:

map.computeIfAbsent("Salt", k -> new HashMap<>())
    .put("Salt", 0);
map.computeIfAbsent("Salt", k -> new HashMap<>())
    .put("Pepper", 1);

Then, for your examples:

  1. map.getOrDefault("Salt", emptyMap()).keySet())
  2. map.getOrDefault("Salt", emptyMap()).get("Salt")
  3. map.getOrDefault("Salt", emptyMap()).get("Pepper")

Upvotes: 2

Related Questions