简体   繁体   中英

JAVA: Return all key values from Hashmap

I'm at the end of writing some code that will manage a 'dummy' train/subway network of stations. I have implemented it using a Map of type Map (String), (List)(String). The final method (the one I'm now struggling with) Should return all the 'stations' that have been added to the network, without duplicates. I'm trying to just get the values to return at the moment, however any advice on both issues would be appreciated. I've included below how I've set up the map, and the method in question. Ideally i'd like these values to be returned as an array, but the compiler seems to be taking some issue with my syntax. Thanks again!

public class MyNetwork implements Network {

Map<String, List<String>> stations = new HashMap<>();

@Override
public String[] getStations() {
 /**
 * Get all stations in the network.
 * @return An array containing all the stations in the network, with no
 * duplicates.
 */

return stations.toArray(new String[0]);

}

See the keySet() method of maps, and to go further, see the toArray() method of sets.

A small code sample would look something like this:

public String[] getStations() {
        /* the reason you need to give the new String array to the toArray() method is, 
        so that the compiler knows that it is in fact an array of String, not just plain array of object */
        return stations.keySet().toArray(new String[0]);
}

如果需要元素数组,请参见map.keySet()。toArray()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM