-3

I have an arraylist of Strings:

ArrayList<String> list = Arrays.asList("A", "B", "C", "D");

I would like to initialize a map HashMap<String, List<Integer>> with the element of my list being the key and an empty list of integers being the value.

Of course there is a way to do it using a loop, but I wonder whether there is a way to do it in one line. After seeing the questions and answers in a similar question, I am aware that it is doable by:

HashMap<String, List<Integer>> bigMap = ImmutableMap.<String, List<Integer>>builder()
.put("A", new ArrayList<Integer>)
.put("B", new ArrayList<Integer>)
.put("C", new ArrayList<Integer>)
.put("D", new ArrayList<Integer>)
.build();

But that only applies to the scenario that the size of the list is small. How can I do it using stream, like the way mentioned in another question?

jsh6303
  • 2,010
  • 3
  • 24
  • 50
  • Did you read [this answer](https://stackoverflow.com/a/20887747/1746118) from the linked question? Could you explain what your question above that is? – Naman Sep 02 '19 at 13:41
  • @Naman yes but that answer gives an example where it maps to the value, not the key, and it uses function `getKey` as the key which is different from what I have. – jsh6303 Sep 02 '19 at 13:43
  • The question you've asked about is using streams, the answer linked shares an approach of doing that. In your case, constant value in the map as the value works instead, `e -> Collections.emptyList()`. Just give it a try at least. – Naman Sep 02 '19 at 13:46

1 Answers1

1

Use Collectors.toMap():

Map<String,List<Integer>> bigMap =
    list.stream()
        .collect(Collectors.toMap(Function.identity(),e-> new ArrayList<Integer>()));
Eran
  • 387,369
  • 54
  • 702
  • 768
  • or `e -> Collections.emptyList()` if that's better read. – Naman Sep 02 '19 at 13:43
  • 1
    @Naman That would populate the `Map` with immutable empty `List`s. If the OP doesn't want to add elements to those `List`s, why create this `Map` in the first place? – Eran Sep 02 '19 at 13:46
  • I thought the question focussed on immutability from the sample code `ImmutableMap.>builder`. Anyway, what you said makes sense for the actual use cases. – Naman Sep 02 '19 at 13:47