地图的通用自动修改功能

时间:2015-08-26 09:54:55

标签: java generics dictionary autovivification

如何使用泛型创建vivify密钥?这段代码甚至无法编译:

/* populate the map with a new value if the key is not in the map */
private <K,V> boolean autoVivify(Map<K,V> map, K key)
{
  if (! map.containsKey(key))
  {
    map.put(key, new V());
    return false;
  }
  return true;
}

1 个答案:

答案 0 :(得分:5)

在Java-8中提供Supplier并使用computeIfAbsent是合理的:

private <K,V> boolean autoVivify(Map<K,V> map, K key, Supplier<V> supplier) {
    boolean[] result = {true};
    map.computeIfAbsent(key, k -> {
      result[0] = false;
      return supplier.get();
    });
    return result[0];
}

用法示例:

Map<String, List<String>> map = new HashMap<>();
autoVivify(map, "str", ArrayList::new);

请注意,与containsKey/put不同,使用computeIfAbsent的解决方案对于并发映射是安全的:不会发生竞争条件。

相关问题