5

Usually, if I know beforehand all the keys of a map, I instantiate it like this:

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

    for (String key : someKeyList) {
        someMap.put(key, null);
    }

Is there any way to do this directly without needing to iterate through the list? Something to the effect of:

new HashMap<String, Object>(someKeyList)

My first thought was to edit the map's keyset directly, but the operation is not supported. Is there other way I'm overlooking?

lv.
  • 446
  • 6
  • 18

1 Answers1

7

You can use Java 8 Streams :

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

Note that if you want a specific Map implementation, you'll have to use a different toMap method, in which you can specify it.

Eran
  • 387,369
  • 54
  • 702
  • 768