将哈希映射转换为 2D 数组

2022-09-02 12:41:39

将HashMap转换为2D数组的最简单方法是什么?


答案 1
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++;
}

答案 2

仅当键和值的类型相同时,才能执行此操作。

鉴于:

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++;
}