-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()]);
4
  • 1
    see: stackoverflow.com/questions/3293946/… Commented Nov 15, 2013 at 10:15
  • and get the keys by i think the command is .keySet() and values by calling values() but im not sure if the commands are exactly that Commented Nov 15, 2013 at 10:15
  • Check this thread stackoverflow.com/questions/12960265/… Commented Nov 15, 2013 at 10:16
  • if you would have googled it, you would have had thousands results on this, and this is not even related to android. No offence. Commented Nov 15, 2013 at 10:19

4 Answers 4

2

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

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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()]);

2 Comments

by String[] strings = keys.toArray(new String[]); have I a Error java: array dimension missing
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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.