Java - 从文字值对中实例化哈希映射

时间:2015-12-27 19:08:07

标签: java hashmap literals

我想用Java中的文字实例化Java hashmap。我使用的是Java 8.

我从Java函数编程中看到,您可以使用列表执行此操作:

final List<String> cities = Arrays.asList("Albany", "Boulder", "Chicago", "Denver", "Eugene");

但我还没有看到你如何用哈希地图做类似的事情。

我可以像这样创建哈希映射:

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正在构建每行指令的hashmap。它可能是。

为了比较,我认为C ++中的以下示例是可能的:

#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;
}

1 个答案:

答案 0 :(得分:1)

由于您使用的是Java 8,因此您可以使用流和收集器来实现此目的。

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));

它非常冗长,但与静态初始化方法相比具有明显的优势 - 以这种方式实例化地图的类不会被它引用。在静态初始化的情况下,使用new HashMap<>(){...}创建的匿名类将保存对创建它的类的引用,而后者在映射本身之前不能进行垃圾回收。