Java: how to convert HashMap to array

前端 未结 12 1961
时光取名叫无心
时光取名叫无心 2020-11-29 16:36

I need to convert a HashMap to an array; could anyone show me how it\'s done?

12条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 17:20

    Map map = new HashMap();
    map.put("key1", "value1");
    map.put("key2", "value2");
    
    Object[][] twoDarray = new Object[map.size()][2];
    
    Object[] keys = map.keySet().toArray();
    Object[] values = map.values().toArray();
    
    for (int row = 0; row < twoDarray.length; row++) {
        twoDarray[row][0] = keys[row];
        twoDarray[row][1] = values[row];
    }
    
    // Print out the new 2D array
    for (int i = 0; i < twoDarray.length; i++) {
        for (int j = 0; j < twoDarray[i].length; j++) {
            System.out.println(twoDarray[i][j]);
        }
    }
    

提交回复
热议问题