java - 动态更新键的 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 的值吗?请指教..
解决方案
入口.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()){
...
}
推荐阅读
- python - 如何在 PyTorch 模型中查找中间层的输入层名称?
- java - 在android中不请求许可,程序直接运行到拒绝块
- javascript - desktopCapturer.getSources() 需要 600 毫秒来做截图 electronjs
- laravel - Laravel:即使没有点击,通知也会消失
- grafana - 如何更新grafana中的文本框值
- r - 与 NSE 和闪亮输入一起使用的 R 函数
- c# - 使用 FormCollection 时在 C# mvc 5 中进行验证的最佳方法是什么
- javascript - 数据表静态html在分页前加载了所有行
- autocomplete - Angular 12 自动完成功能不会通过可观察的 valueChange 触发
- javascript - 将数组中的项目添加到 HTML 表