Convert Hash Map to Array

I have a hashmap like this:

HashMap<String, String[]> map = new HashMap<String, String[]>(); 

I want to convert this to an array, for example Temp [], containing the key from hashmap as the first value and the second String [] array from the map, as well as an array. Is it possible? How?

+4
source share
4 answers

See the same question here :

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

Hm. Your question is really strange, but here is what you asked:

 HashMap<String, String[]> map = new HashMap<String, String[]>(); String[] keys = map.keySet().toArray(); Object[] result = new Object[keys.length*2]; //the array that should hold all the values as requested for(int i = 0; i < keys.length; i++) { result[i] = keys[i]; //put the next key into the array result[i+1] = map.get(keys[i]); //put the next String[] in the array, according to the key. } 

But man, why would you ever need something like that? No matter what you want to do, the chance is more than 99% that you do not need to write something like this ...

+1
source

I think you just need to write a method that does what you want.

0
source

I'm not sure if this is what you need, but here is your code I changed:

  Map<String, String[]> map = new HashMap<String, String[]>(); map.put("key1", new String[]{"value1", "test1"}); map.put("key2", new String[]{"value2"}); Object[] keys = map.keySet().toArray(); Object[] values = map.values().toArray(); System.out.println("key = " + keys[0] + ", value #1 = " + ((Object[])values[0])[0]); System.out.println("key = " + keys[1] + ", value #1 = " + ((Object[])values[1])[0] + ", value #2 = " + ((Object[])values[1])[1]); 

Output:

 key = key2, value #1 = value2 key = key1, value #1 = value1, value #2 = test1 

Note that in the key[0] section, instead of "key1" is "key2" . This is because HashMap does not save the keys in the same order that you add them. To change this, you must choose a different Map implementation (e.g. TreeMap if you want to have an alphabetical order).

How it works? Java allows you to create arrays up to Object . toArray() returns an Object[] - an array of Objects , but these objects are also arrays (from String - as you defined on your map)! If you print only value[0] , it will be like printing mySampleArray , where mySampleArray :

 Object[] mySampleArray = new Object[5]; 

So you call it not an element on the whole array. That is why you get [Ljava.lang.String;@7c6768 etc. (Which is the className @HashCode - this is what the default toString() method does).

To get to your element, you must go deeper.

 ((Object[])values[0])[0] 

This means: take the values ​​[0] (we know that it contains an array), attribute it to the array and take the first element.

Hope this helps, let me know if you need more information.

0
source

Source: https://habr.com/ru/post/1343883/


All Articles