-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?

3
  • Did you read this answer from the linked question? Could you explain what your question above that is? Commented Sep 2, 2019 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. Commented Sep 2, 2019 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. Commented Sep 2, 2019 at 13:46

1 Answer 1

1

Use Collectors.toMap():

Map<String,List<Integer>> bigMap = list.stream() .collect(Collectors.toMap(Function.identity(),e-> new ArrayList<Integer>())); 
Sign up to request clarification or add additional context in comments.

3 Comments

or e -> Collections.emptyList() if that's better read.
@Naman That would populate the Map with immutable empty Lists. If the OP doesn't want to add elements to those Lists, why create this Map in the first place?
I thought the question focussed on immutability from the sample code ImmutableMap.<String, List<Integer>>builder. Anyway, what you said makes sense for the actual use cases.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.