Home > Software design >  Inititialize Map keys from list with a default value
Inititialize Map keys from list with a default value

Time:12-09

I need to initialize the keys of a map from a list and give a default value for each entry. Currently I use a for loop :

Map<String, String > myMap = new HashMap<>();
List<String> keys = Arrays.asList("a", "b", "c", "d");
for (String key : keys){
    myMap.put(key, "default");
}

Is there a cleaner way to do that ? Stream or lambda maybe ?

CodePudding user response:

Yes, you can create a Stream of that List's elements and collect them to a Map:

Map<String,String> map = keys.stream ()
                             .collect (Collectors.toMap (Function.identity (), 
                                                         k -> "default"));
  • Related