Java:如何将 HashMap<String, Object> 转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1090556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:33:24  来源:igfitidea点击:

Java: how to convert HashMap<String, Object> to array

javaarrayscollectionshashmap

提问by burntsugar

I need to convert a HashMap<String, Object>to an array; could anyone show me how it's done?

我需要将 a 转换HashMap<String, Object>为数组;谁能告诉我它是怎么做的?

采纳答案by Landon Kuhn

hashMap.keySet().toArray(); // returns an array of keys
hashMap.values().toArray(); // returns an array of values


Edit

编辑

It should be noted that the ordering of both arrays may not be the same, See oxbow_lakes answer for a better approach for iteration when the pair key/values are needed.

需要注意的是,两个数组的顺序可能不同,请参阅 oxbow_lakes answer 以获取在需要键/值对时更好的迭代方法。

回答by oxbow_lakes

If you want the keys and values, you can always do this via the entrySet:

如果你想要键和值,你总是可以通过entrySet

hashMap.entrySet().toArray(); // returns a Map.Entry<K,V>[]

From each entry you can (of course) get both the key andvalue via the getKeyand getValuemethods

从每个条目中,您(当然)可以通过和方法获取键getKeygetValue

回答by valerian

Map<String, String> map = new HashMap<String, String>();
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]);
    }
}

回答by kmccoy

If you have HashMap<String, SomeObject> hashMapthen:

如果你有HashMap<String, SomeObject> hashMap那么:

hashMap.values().toArray();

Will return an Object[]. If instead you want an array of the type SomeObject, you could use:

将返回一个Object[]. 如果你想要一个 type 的数组SomeObject,你可以使用:

hashMap.values().toArray(new SomeObject[0]);

回答by CrackerHyman9

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.

为了保证每个键和值数组的正确顺序,请使用它(其他答案使用单独的Sets,它们不提供顺序保证。

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

回答by Dean Wild

An alternative to CrackerHymans suggestion, if you want the HashMap to maintain order you could consider using a LinkedHashMap instead. As far as im aware it's functionality is identical to a HashMap but it is FIFO so it maintains the order in which items were added.

CrackerHymans 建议的替代方案,如果您希望 HashMap 保持顺序,您可以考虑使用 LinkedHashMap 代替。据我所知,它的功能与 HashMap 相同,但它是 FIFO,因此它保持添加项目的顺序。

回答by Mayur

You may try this too.

你也可以试试这个。

public static String[][] getArrayFromHash(Hashtable<String,String> data){
        String[][] str = null;
        {
            Object[] keys = data.keySet().toArray();
            Object[] values = data.values().toArray();
            str = new String[keys.length][values.length];
            for(int i=0;i<keys.length;i++) {
                str[0][i] = (String)keys[i];
                str[1][i] = (String)values[i];
            }
        }
        return str;
    }

Here I am using String as return type. You may change it to required return type by you.

这里我使用 String 作为返回类型。您可以将其更改为所需的返回类型。

回答by Mitul Maheshwari

To Get in One Dimension Array.

进入一维数组。

    String[] arr1 = new String[hashmap.size()];
    String[] arr2 = new String[hashmap.size()];
    Set entries = hashmap.entrySet();
    Iterator entriesIterator = entries.iterator();

    int i = 0;
    while(entriesIterator.hasNext()){

        Map.Entry mapping = (Map.Entry) entriesIterator.next();

        arr1[i] = mapping.getKey().toString();
        arr2[i] = mapping.getValue().toString();

        i++;
    }


To Get in two Dimension Array.


进入二维数组。

   String[][] arr = new String[hashmap.size()][2];
   Set entries = hashmap.entrySet();
   Iterator entriesIterator = entries.iterator();

   int i = 0;
   while(entriesIterator.hasNext()){

    Map.Entry mapping = (Map.Entry) entriesIterator.next();

    arr[i][0] = mapping.getKey().toString();
    arr[i][1] = mapping.getValue().toString();

    i++;
}

回答by Hugo Tavares

I used almost the same as @kmccoy, but instead of a keySet()I did this

我使用的几乎与@kmccoy 相同,但keySet()我没有这样做

hashMap.values().toArray(new MyObject[0]);

回答by Ali Bagheri

@SuppressWarnings("unchecked")
    public static <E,T> E[] hashMapKeysToArray(HashMap<E,T> map)
    {
        int s;
        if(map == null || (s = map.size())<1)
            return null;

        E[] temp;
        E typeHelper;
        try
        {
            Iterator<Entry<E, T>> iterator = map.entrySet().iterator();
            Entry<E, T> iK = iterator.next();
            typeHelper = iK.getKey();

            Object o = Array.newInstance(typeHelper.getClass(), s);
            temp = (E[]) o;

            int index = 0;
            for (Map.Entry<E,T> mapEntry : map.entrySet())
            {
                temp[index++] = mapEntry.getKey();
            }
        }
        catch (Exception e)
        {
            return null;
        }
        return temp;
    }
//--------------------------------------------------------
    @SuppressWarnings("unchecked")
    public static <E,T> T[] hashMapValuesToArray(HashMap<E,T> map)
    {
        int s;
        if(map == null || (s = map.size())<1)
            return null;

        T[] temp;
        T typeHelper;
        try
        {
            Iterator<Entry<E, T>> iterator = map.entrySet().iterator();
            Entry<E, T> iK = iterator.next();
            typeHelper = iK.getValue();

            Object o = Array.newInstance(typeHelper.getClass(), s);
            temp = (T[]) o;

            int index = 0;
            for (Map.Entry<E,T> mapEntry : map.entrySet())
            {
                temp[index++] = mapEntry.getValue();
            }
        }
        catch (Exception e)
        {return null;}

        return temp;
    }