是否可以使用键列表实例化Map?

lv.*_*lv. 5 java dictionary

通常,如果我事先知道地图的所有键,我会像这样实例化它:

    List<String> someKeyList = getSomeList();
    Map<String, Object> someMap = new HashMap<String, Object>(someKeyList.size());

    for (String key : someKeyList) {
        someMap.put(key, null);
    }
Run Code Online (Sandbox Code Playgroud)

有没有办法直接这样做而不需要遍历列表?有效的东西:

new HashMap<String, Object>(someKeyList)
Run Code Online (Sandbox Code Playgroud)

我的第一个想法是直接编辑地图的键集,但不支持该操作.还有其他方式我可以俯瞰吗?

Era*_*ran 7

您可以使用Java 8 Streams:

Map<String,Object> someMap = 
    someKeyList.stream()
               .collect(Collectors.toMap(k->k,k->null));
Run Code Online (Sandbox Code Playgroud)

请注意,如果您需要特定的Map实现,则必须使用其他toMap方法,您可以在其中指定它.