This works as expected:
Map<String, String> myMap = new ConcurrentSkipListMap<>();
myMap.put("a", "b");
myMap.put("b", "c");
String[] myArray= myMap.keySet().toArray(new String[myMap.size()]);
System.out.println(Arrays.toString(myArray));
and outputs:
[a, b]
Note that this is not atomic so if your map is modified between calling size
and toArray
, the following would happen:
- if the new map is smaller,
myArray
will have a size that is larger than the array you created innew String[myMap.size()]
- if the new map is larger,
myArray
will contain null items
So it probably makes sense to save a call to size
and avoid a (possibly) unnecessary array creation in this case and simply use:
String[] myArray= myMap.keySet().toArray(new String[0]);