Is it possible to create a copy of the Map with a list of keys?

Usually, if I know all the keys of the card in advance, I create 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 a way to do this directly without requiring repetition on the list? Sort of:

 new HashMap<String, Object>(someKeyList) 

My first thought was to edit the map set directly, but the operation is not supported. Is there any other way that I skip?

+5
source share
1 answer

You can use Java 8 threads:

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

Note that if you need a specific Map implementation, you will have to use another toMap method in which you can specify it.

+7
source

Source: https://habr.com/ru/post/1243311/


All Articles