将哈希映射转换为 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<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++;
}