在迭代期间更改 HashMap 键 [英] Changing HashMap keys during iteration

查看:25
本文介绍了在迭代期间更改 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 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆