我创建了一个名为 Foo
的类,该类具有方法 toArray()
,返回类型为 Array<Int>
。
现在我有一个将字符串映射到HashMap的HashMap,它将对象映射到Foo。也就是说:
HashMap<String,HashMap<Object,Foo>>
我想要创建一个新的类型对象:
HashMap<String,HashMap<Object,Array<Int>>>
这是通过对原始HashMap中的每个元素Foo调用toArray()函数来获取的。
为此,我通常会执行以下操作:
public static HashMap<String,HashMap<Object,Array<Int>>> changeMap(Map mpOld) {
Object key2;
String key1;
Iterator it2;
HashMap<String,HashMap<Object,Array<Int>>> mpNew=
new HashMap<String,HashMap<Object,Array<Int>>>()
Iterator it1 = mpOld.keySet().iterator();
while (it1.hasNext()) {
key1=it1.next();
it2= mpOld.get(key1).keySet().iterator();
mpNew.put(key1,new HashMap<Object,Array<Int>>())
while (it2.hasNext()) {
key2=it2.next();
mpNew.get(key1).put(key2,mpOld.get(key1).get(key2).toArray());
//TODO clear entry mpOld.get(key1).get(key2)
}
//TODO clear entry mpOld.get(key1)
}
return mpNew;
}
类似的代码运行良好,但是HashMap的大小太大了,无法在内存中容纳两个HashMap。您可以看到我添加了两个点,我想在这里清除一些条目。问题是,如果我这样做,要么会出现并发错误,要么迭代器循环会终止。
我想知道是否有更好的方法来遍历Map并复制信息。
此外,我正在一个Scala项目中工作,但是在这里我必须使用Java类型进行某些兼容性问题。尽管Java.util.HashMap不是迭代器,但Scala可能有一些隐藏的功能来处理这个问题吗?
谢谢。