Java - instantiate a hashmap from literal value pairs
本问题已经有最佳答案,请猛点这里访问。
我想用Java中的文字实例化Java哈希映射。我使用的是Java 8。
我从Java书中的函数编程中看到,你可以用列表来完成:
1 |
但是我还没有看到如何用散列图做类似的事情。
我可以这样创建散列图:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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")); } } |
但是这种语法意味着Java正在构建每行指令的HASMAP。可能是这样。
为了比较,C++中的例子是我认为可能的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #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; } |
由于使用Java 8,可以使用流和收集器来实现这一点。
1 2 3 4 5 6 7 8 9 10 | import java.util.AbstractMap.SimpleEntry; import java.util.stream.Collectors; import java.util.stream.Stream; ... Map<String, String> map = Stream.of( new SimpleEntry<>("key1","value1"), new SimpleEntry<>("key2","value2")) .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)); |
它相当冗长,但与静态初始化方法相比有很大的优势——以这种方式实例化映射的类不被它引用。在静态初始化的情况下,使用