There's no need to explicitly iterate over the values in the Map
, just use built-in methods. The whole getConnections()
implementation can be written in a single line:
return stations.get(fromStation).toArray(new String[0]);
How it works:
- First we obtain the list of connections for a given station, using
get()
- The previous step returns a
List<String>
- Now we only need to convert it to a
String[]
usingtoArray()
. For type safety we pass an array of the expected return type
Alternatively, you could also change the return type to List<String>
, unless strictly necessary there's no need to convert a List
to an array; if you decide to do this the toArray()
call would be unnecessary.