gpt4 book ai didi

java - 在 Java(或 Scala)中迭代 HashMap 的 HashMap

转载 作者:IT王子 更新时间:2023-10-28 23:38:44 25 4
gpt4 key购买 nike

我创建了一个类 Foo有方法toArray()返回 Array<Int> .

现在,我有一个 HashMap 将 Strings 映射到 HashMaps,它将 Objects 映射到 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 的大小太大而无法在内存中容纳其中两个。如您所见,我添加了两个要清除某些条目的点。问题是,如果这样做,我会收到并发错误,或者迭代器循环会终止。

我想知道是否有更好的方法来遍历 map 并复制信息。

另外,我在一个 Scala 项目中工作,但在这里我必须使用 Java 类型来解决一些兼容性问题。虽然 Java.util.HashMap不是迭代器,也许 Scala 有一些隐藏的功能来处理这个?

谢谢,

最佳答案

迭代器提供 remove(..) 方法,可以安全地删除之前访问过的项目。遍历映射的键/值条目,转换它们并将它们添加到新映射中,并在你去的时候删除旧的。

/**
* Transfers and converts all entries from <code>map1</code> to
* <code>map2</code>. Specifically, the {@link Foo} objects of the
* inner maps will be converted to integer arrays via {@link Foo#toArray}.
*
* @param map1 Map to be emptied.
* @param map2 Receptacle for the converted entries.
*/
private static void transfer(Map<String, Map<Object, Foo>> map1
, Map<String, Map<Object, int[]>> map2) {

final Iterator<Entry<String, Map<Object, Foo>>> mapIt
= map1.entrySet().iterator();
while (mapIt.hasNext()) {
final Entry<String, Map<Object, Foo>> mapEntry = mapIt.next();
mapIt.remove();
final Map<Object, int[]> submap = new HashMap<Object,int[]>();
map2.put(mapEntry.getKey(), submap);
final Iterator<Entry<Object,Foo>> fooIt
= mapEntry.getValue().entrySet().iterator();
while (fooIt.hasNext()) {
final Entry<Object,Foo> fooEntry = fooIt.next();
fooIt.remove();
submap.put(fooEntry.getKey(), fooEntry.getValue().toArray());
}
}
}

关于java - 在 Java(或 Scala)中迭代 HashMap 的 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3254072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com