是否存在具有不同值类型的多图

时间:2019-05-07 08:58:22

标签: java dictionary collections

我的应用程序需要一个多值映射,该键的键具有2种类型的值,例如List和String。 Map可以基于类型参数返回所有值或单个值,如get(key,type)一样。

在spring或apache多值地图中都找不到这样的功能。 是否有其他图书馆提供这种数据结构,还是我必须实现自己的图书馆?

3 个答案:

答案 0 :(得分:0)

创建自己的对象

public class YourOwnObject {

    private HashMap<String,String> valuesMap
    private ArrayList<String> valuesList;

}

以及当您实例化地图时:

Map<String,YourOwnObject>

如果您采用这种方式,您可以自由地做任何事情

答案 1 :(得分:0)

在Java 8中使用带有期望值的lamda表达式添加多图有点容易。这是示例代码。您可以尝试一下。

public class TestMultiMap<K, V> {

    private final Map<K, Set<V>> multiValueMap = new HashMap<>();

    public void put(K key, V value) {
        this.multiValueMap.computeIfAbsent(key, k -> new HashSet<>()).add(value);
    }   
    public Set<V> get(K key) {
        return this.multiValueMap.getOrDefault(key, Collections.emptySet());
    }
}

computeIfAbsent()方法采用A键和lambda。如果该密钥不存在,则运行executeIfAbsent()并创建新的HashMap。

如果发现键为空,则getOrDefault()方法将返回值或返回空集。

要使用此

TestMultiMap<String,Object> testMultiMap = new TestMultiMap<>();
testMultiMap.put("Key 1", new Object());
testMultiMap.put("Key 2", "String 1");
testMultiMap.put("Key 3", 1);

答案 2 :(得分:0)

怎么样:

Map<String, Map<Class<?>, Object>> valuesByTypeByKey;

获取时,请提供keytype

public <T> T fetch(String key, Class<T> type) {
    return (T)valuesByTypeByKey.getOrDefault(key, Collections.emptyMap()).get(type);
}

插入操作如下:

public <T> void insert(String key, Class<T> type, T value) {
    valuesByTypeByKey.computeIfAbsent(key, k -> new HashMap<>()).put(type, value);
}
相关问题