-3

Here is the code:

HashMap<String, Integer> arr = new HashMap<String, Integer>(); 
arr.put("one", 1); 
arr.put("two", 2); 
arr.put("three", 3); 

how can I to get all strings as String[] array and all integers as Int[] array?


thanks to all! all is correct, if somebody has the same Problemm, answer is:

String[] entry =(String[])arr.keySet().toArray(new String[arr.size()]);
Integer[] entry_values =(Integer[])arr.values().toArray(new Integer[arr.size()]);
user2995801
  • 115
  • 7

4 Answers4

2

1) arr.keySet().toArray(new String[arr.size()]);

2) arr.values().toArray(new Integer[arr.size()]);

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

You can use the keySet() and values() methods to get the strings and integers alone. They both return collections, so you can then call toArray on them.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121
1

There is no Method to get your Items by their type, but by their function in the map.

HashMap<String, Integer> arr = new HashMap<String, Integer>();     
Set<String> keys = arr.keySet(); // all keys.
Collection<Integer> values = arr.values(); //all values.

you can call toArray() on both of your results. Add a new Array as argument to define the type of the result.

String[] strings = keys.toArray(new String[arr.size()]);
Integer[] ints = values.toArray(new Integer[arr.size()]);
Simulant
  • 19,190
  • 8
  • 63
  • 98
  • by String[] strings = keys.toArray(new String[]); have I a Error java: array dimension missing – user2995801 Nov 15 '13 at 10:45
  • you can add any size, if the size is to small a new array with the right dimension is created. Adding the right dimension saves this operation. – Simulant Nov 15 '13 at 10:50
0

Try this out:

String strArr[] = new String[arr.size()];
arr.keySet().toArray(strArr); // Populate the String array with map keys

Integer intArr[] = new Integer[arr.size()];
arr.values().toArray(intArr); // Populate the Int array with map values
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38