半唯一的嵌套Java映射?



我已经看到了一些关于这个问题的问题,但没有一个真正与我想要做的事情有关的问题。

我需要的示例:

我有一个键(字符串(,键(字符串(,值(整数(:

"盐", "盐", 0

"盐", "胡椒", 1

我希望能够调用:

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

我尝试过嵌套链接/哈希映射,但添加第二个盐值会覆盖第一个......而且我不知道如何拥有它,因此第二个密钥不会覆盖第一个密钥。

您可以使用Map<String, Map<String, Integer>>

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

添加如下值:

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

然后,对于您的示例:

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

您可以通过以下类来实现此目的。请参阅此处的工作代码:

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);
}
}

以下是供使用的示例代码:

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")); 

输出

[Salt, Pepper]
1

最新更新