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?

YCF_L
  • 51,266
  • 13
  • 85
  • 129
Yoda
  • 16,053
  • 60
  • 184
  • 315
  • @Aman your solution will not compile – YCF_L Oct 19 '20 at 09: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->` – Aman Oct 19 '20 at 09:32

1 Answers1

2

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<>()));
YCF_L
  • 51,266
  • 13
  • 85
  • 129
  • 1
    That `Function.identity()` is a nice math reference, just not sure if programmers think it's a clear code. Thanks. – Yoda Oct 19 '20 at 10:39