I have a map<String, Object>
and an array of int[]
which is supposed to contain the map keys.
Is there a nice and short way to convert the keys to int, without using a loop?
myArray = myMap.keySet().toArray(new int[5]);
I useJava 8
.
Thanks!
I have a map<String, Object>
and an array of int[]
which is supposed to contain the map keys.
Is there a nice and short way to convert the keys to int, without using a loop?
myArray = myMap.keySet().toArray(new int[5]);
I useJava 8
.
Thanks!
Assuming all your String
keys can be safely parsed as integers :
int[] keys = myMap.keySet().stream().mapToInt(Integer::parseInt).toArray();
keySet()
returns a Set<String>
.stream()
returns a Stream<String>
.mapToInt()
maps that Stream<String>
to an IntStream
by applying Integer.parseInt()
on each String
.toArray()
returns an array of all the elements of the IntStream
. myMap.keySet().toArray(); // returns an array of keys
myMap.values().toArray(); // returns an array of values
Attention! Should be noted that the ordering of both arrays may not be the same.