Changing HashMap keys during iteration(在迭代期间更改 HashMap 键)
问题描述
是否可以在迭代期间更改同一 HashMap 实例的键?因为地图条目集没有方法entry.setKey().现在我能想到的是创建另一个 HashMap...
is it possible to change keys of a the same HashMap instance during iteration ? Because map entry set don't have a method entry.setKey(). Now what I can think off is create another HashMap...
MultipartParsingResult parsingResult = parseRequest(request);
Map<String, String[]> mpParams = parsingResult.getMultipartParameters();
Map<String, String[]> mpParams2 = new HashMap<String, String[]>();
Iterator<Entry<String,String[]>> it = mpParams.entrySet().iterator();
while (it.hasNext()) {
Entry<String,String[]> entry = it.next();
String name = entry.getKey();
if (name.startsWith(portletNamespace)) {
mpParams2.put(name.substring(portletNamespace.length(), name.length()), entry.getValue());
}
else {
mpParams2.put(name, entry.getValue());
}
}
推荐答案
您应该将信息保留在其他集合中,以便在迭代后对其进行修改.您只能在迭代器期间使用 iterator.remove() 删除条目.HashMap 合约禁止在迭代期间对其进行变异.
You should keep information in other collection to modify it after iteration. You can only remove entry using iterator.remove() during iterator. HashMap contract forbids mutating it during iteration.
这篇关于在迭代期间更改 HashMap 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在迭代期间更改 HashMap 键
基础教程推荐
- JPA惰性列表上的流 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
