将HashMap转换为2D数组的最简单方法是什么?
将HashMap转换为2D数组的最简单方法是什么?
HashMap map = new HashMap();
Object[][] arr = new Object[map.size()][2];
Set entries = map.entrySet();
Iterator entriesIterator = entries.iterator();
int i = 0;
while(entriesIterator.hasNext()){
Map.Entry mapping = (Map.Entry) entriesIterator.next();
arr[i][0] = mapping.getKey();
arr[i][1] = mapping.getValue();
i++;
}
HashMap map = new HashMap();
Object[][] arr = new Object[map.size()][2];
Set entries = map.entrySet();
Iterator entriesIterator = entries.iterator();
int i = 0;
while(entriesIterator.hasNext()){
Map.Entry mapping = (Map.Entry) entriesIterator.next();
arr[i][0] = mapping.getKey();
arr[i][1] = mapping.getValue();
i++;
}
只有当键和值的类型相同时,才能执行此操作。
鉴于:
HashMap<String,String> map;
我可以使用这个简单的循环从这个地图创建一个数组:
String[][] array = new String[map.size()][2];
int count = 0;
for(Map.Entry<String,String> entry : map.entrySet()){
array[count][0] = entry.getKey();
array[count][1] = entry.getValue();
count++;
}
怎么样
Object[][] array = new Object[][]{map.keySet.toArray(), map.entrySet.toArray()};
或者,为了更具体地说明类型,让我们说它们是 Strings
: Set
的 toArray
采取提示论证,这样
String[][] array = new String[][]{map.keySet.toArray(new String[0]), map.entrySet.toArray(new String[0])};
编辑: 几天后我才意识到这一点 可能 偶然工作,一般不应该。原因是中间体 Set
;虽然它是“由地图支持”,但似乎没有明确保证它将以任何特定顺序迭代。因此,密钥和入口阵列可能不是相同的顺序,这肯定是一场灾难!
使用迭代迭代你的Map 的entrySet,并使用Entry对象填充数组记录