Java: how to convert HashMap to array

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

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

12条回答
  •  萌比男神i
    2020-11-29 17:05

    To guarantee the correct order for each array of Keys and Values, use this (the other answers use individual Sets which offer no guarantee as to order.

    Map map = new HashMap();
    String[] keys = new String[map.size()];
    Object[] values = new Object[map.size()];
    int index = 0;
    for (Map.Entry mapEntry : map.entrySet()) {
        keys[index] = mapEntry.getKey();
        values[index] = mapEntry.getValue();
        index++;
    }
    

提交回复
热议问题