Create Map initialized using keys in given List

Viewed 86

I have a list List<String> entries I would like to create a HashMap<String, Deque<Instant>> map with keys being those from entries list.

I could do

for(String s: entries){map.put(s, new Deque<>()} however I'm looking for more elegant solution.

map = Stream.of(entries).collect(Collectors.toMap(x -> (String) x, new Deque<>()));

however I get casting error. Is that fixable, can I constuct a map from list of keys?

1 Answers

I think you need this:

Map<String, Deque<Instant>> map = entries.stream()
        .collect(Collectors.toMap(x -> x, x -> new ArrayDeque<>()));

You can even replace x -> x by Function.identity():

.collect(Collectors.toMap(Function.identity(), x -> new ArrayDeque<>()));
Related