2

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?

2
  • @Aman your solution will not compile Commented Oct 19, 2020 at 9:24
  • entries.stream().collect(Collectors.toMap(Function.identity(), x -> new ArrayDeque())) or Collectors.toMap(Function.identity(), x -> new LinkedList()) should be fine. @YCF_L yes, forgot the x-> Commented Oct 19, 2020 at 9:32

1 Answer 1

3

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<>()));
Sign up to request clarification or add additional context in comments.

1 Comment

That Function.identity() is a nice math reference, just not sure if programmers think it's a clear code. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.