首页 > 解决方案 > 动态更新键的 Map 值

问题描述

我有一个 Map ,其中将 registrationID 作为键,并将为该注册 ID 存储的信息的整个 filePath 作为值。我想根据一些条件检查动态更改该路径的值。

void getDetails(final Map<String, String> detailsMap){

String filePath =  new File(details.entrySet().iterator().next().getValue()).getParent();
// key: 101A90Q  value : C:\Users\xyy\registeredDetails\101A90QInfo\101A90QInfo.xlsx
//sometimes the value of the detailsMap is dynamically changed (only the path, filename remains same) 

//logic to get the dynamic path
if(someCondCheck)
    filePath =  "c:\users\xyy\registeredDetails\conference"; //new path, but the filename i need to take from the old filePath value mentioned above. (101A90QInfo.xlsx)
}
//i want to update the map (detailsMap) with the above mentioned filePath along with the filename

   showRegisteredCompleteInfo(detailsMap);
}

我想更新 detailsMap ,它的值C:\Users\xyy\registeredDetails\101A90QInfo\101A90QInfo.xlsx与更新后的文件路径以及最初提到的文件名一样c:\users\xyy\registeredDetails\conference\101A90QInfo.xlsx。我可以在不再次迭代的情况下更新 Map 的值吗?请指教..

标签: java

解决方案


入口.setValue

您正在Entry使用该集合中的第一个

String filePath =  new File(details.entrySet().iterator().next().getValue()).getParent();

您可以将其保留Entry在内存中以便key以后获取。

Entry<String, String> e = details.entrySet().iterator().next();
String filePath = new File(e.getValue()).getParent();

...

e.setValue(filePath);

正如条目 javadoc所提到的:

用指定的值替换与该条目对应的值(可选操作)。(写入映射。)如果映射已经从映射中删除(通过迭代器的删除操作),则此调用的行为是未定义的。

地图.put

或者直接在地图上使用键:

details.put(e.getKey(), filePath);

笔记

您将获得 entrySet 中的第一个项目,它不会给您任何关于它的确定性。如果要迭代集合,则需要更新代码以使用循环读取它:

for(Entry<String, String> e : details.entrySet()){
     ...
}

推荐阅读