Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to instantiate a Map with a list of keys?

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?

like image 597
lv. Avatar asked Feb 18 '16 10:02

lv.


People also ask

Can we use list as key in map?

Yes you can have ArrayList s as a keys in a hash map, but it is a very bad idea since they are mutable.

Can a map have more than one key?

Class MultiKeyMap<K,V> A Map implementation that uses multiple keys to map the value. This class is the most efficient way to uses multiple keys to map to a value.

Can a HashMap have multiple values for same key?

In these cases, we can use Collections such as list, set, etc. to insert multiple values into the same key in HashMap.


1 Answers

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.

like image 57
Eran Avatar answered Oct 19 '22 01:10

Eran