1

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!

dardy
  • 433
  • 1
  • 6
  • 18

2 Answers2

7

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.
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Nice explanation. I'd emphasize that `safely parsed` portion though along with the question why the keys are strings if they are safely parseable (i.e. represent integers anyways). – Thomas Oct 06 '16 at 08:42
0
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.

  • Do you have any example of a `Map` that allows different iteration order for keys and values? I did ask a [question about that](http://stackoverflow.com/questions/34989708/is-iteration-order-over-the-different-collection-views-of-a-given-map-guaranteed) a while ago but the results where not quite conclusive. It seemed from the docs that if an iteration order is specified for a map, it is required to be the same for all 3 views (entrySet, keySet and values). – Hulk Oct 06 '16 at 12:12
  • It depends on the concrete implementation of Map interface. For example imagine u have very stupid implementation after any operation that randomly shuffles the elements. In this case it is almost certain that when call keyset() gets a different order than when call values(). Basic implementation of Maps isnt anything like that but if you use Hashtable so for example if call barring feature so you can paste it somewhere into the middle and the end of which it follows that changing the order of application of certain elements. – thomas.adamjak Oct 07 '16 at 09:27
  • The second reason is that the method keyset () returns a class set and that is not a guaranteed order. Anyway, these are also extremely'll encounter rarely. – thomas.adamjak Oct 07 '16 at 09:28