给定由LinkedLists组成的java hashmap中的键,如何更新值?

时间:2016-10-18 16:07:02

标签: java list linked-list hashmap

这是我的HashMap

HashMap<String, LinkedList<LinkedList<String>>> partitionMap = new HashMap<String, LinkedList<LinkedList<String>>>();

我知道使用put方法可以工作,例如:

hashmap.put(key, hashmap.get(key) + 1);

但是在这个示例中我们有Integer,在我的情况下我有一个LinkedList<LinkedList<String>>>

有没有办法做同样的事情?

3 个答案:

答案 0 :(得分:2)

put仍然有效。您可以在地图中添加一对新的String,LinkedList<LinkedList<String>>

LinkedList<LinkedList<String>> aList = new LinkedList<LinkedList<String>>();
hashmap.put("aString", aList);

或者,更简洁

hashmap.put("aString", new LinkedList<>());

然后修改地图中的链接列表get,然后修改它。

hashmap.get("aString").add(new LinkedList<String>());

您不需要将修改后的列表放回地图中。当您在地图中获得对列表的引用时,您正在修改当前在地图中的列表。

顺便说一句,您确定是否需要LinkedList<LinkedList<String>>?访问外部LinkedList中的任意LinkedList将花费线性时间,这意味着编辑其中一个嵌套LinkedLists的内容将采用(最佳情况)线性时间,并且可能与二次方案一样糟糕。

我建议改为ArrayList<List<String>>(或List<List<String>>实例化为ArrayList<List<String>>。这样,您可以在固定时间内访问任意嵌套列表,并且嵌套列表中使用的特定List实现保持打开状态。

答案 1 :(得分:0)

是的,当然:

LinkedList<LinkedList<String>>> list = hashmap.get(key);
LinkedList<LinkedList<String>>> updatedList = updateListValue(list);
hashmap.put(key, updatedList);

现在,updateListValue(LinkedList<LinkedList<String>>> list)的代码当然取决于您的意思&#34;更新值&#34;。

答案 2 :(得分:0)

如果您使用的是Java8 +,则可以使用方法computecomputeIfPresentcomputeIfAbsent

    HashMap<String, LinkedList<LinkedList<String>>> partitionMap = new HashMap<String, LinkedList<LinkedList<String>>>();
    partitionMap.computeIfAbsent("key-1", key -> new LinkedList<>()); //add
    System.out.println(partitionMap);
    partitionMap.computeIfPresent("key-1", (key, value) -> {value.add(new LinkedList<>()); return value;}); //update
    System.out.println(partitionMap);

compute*方法会返回值

输出

{key-1=[]}
{key-1=[[]]}