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?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Yoda
  • 17,363
  • 67
  • 204
  • 344
  • @Aman your solution will not compile – Youcef LAIDANI 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<>()));
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 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