I want to instantiate a Java hashmap with literals in Java. I am using Java 8.
I have seen from Functional Programming in Java book that you can do this with Lists:
final List<String> cities = Arrays.asList("Albany", "Boulder", "Chicago", "Denver", "Eugene");
But I haven't seen how you can do a similar thing with hash maps.
I can create the hash map like this:
import java.util.HashMap;
import java.util.Map;
public class ShortestPath1 {
public static void main(final String[] args) {
final Map<String,Integer> station2nlc = new HashMap<String, Integer>();
station2nlc.put("Ealing Broadway", 319000);
station2nlc.put("Ealing Common", 319005);
station2nlc.put("Acton Town LT", 50000);
station2nlc.put( "Chiswick Park LT", 54500);
station2nlc.put( "Turnham Green LT", 73400);
station2nlc.put( "Stamford Brook LT", 71300);
station2nlc.put( "Ravenscourt Park LT", 68200);
station2nlc.put( "Hammersmith LT", 59300);
station2nlc.put( "Barons Court LT", 51600);
station2nlc.put( "West Kensington", 76000);
station2nlc.put( "Earls Court LT", 56200);
station2nlc.put( "West Kensington LT", 76000);
System.out.println("Ealing has NLC: " + station2nlc.get("Ealing Broadway"));
}
}
But this syntax implies that Java is building the hashmap per line instruction. Which it probably is.
For comparison, the example below in C++ is what I was thinking would be possible:
#include <string>
#include <unordered_map>
#include <iostream>
int main() {
std::unordered_map<std::string, int> station2nlc(
{
{ "Ealing Broadway", 319000 },
{ "Ealing Common", 319005 },
{ "Acton Town LT", 50000 },
{ "Chiswick Park LT", 54500 },
{ "Turnham Green LT", 73400 },
{ "Stamford Brook LT", 71300 },
{ "Ravenscourt Park LT", 68200 },
{ "Hammersmith LT", 59300 },
{ "Barons Court LT", 51600 },
{ "West Kensington", 76000 },
{ "Earls Court LT", 56200 },
{ "West Kensington LT", 76000 },
});
std::cout << "Ealing has NLC: " << station2nlc["Ealing Broadway"] << std::endl;
}