2

I have a

List<String> lists;

I need to iterate through this lists and put in the LinkedHashMap. Normally I do it as below:

Map<Integer,String> listMap=new LinkedHashMap<>();
for(int pos=0;pos<lists.size();pos++){
    listMap.put(pos,lists.get(pos));
}

How can I do the above operation with streams?

Garry Steve
  • 129
  • 2
  • 11
  • 2
    You might as well have a look at this [question](https://stackoverflow.com/questions/18552005/is-there-a-concise-way-to-iterate-over-a-stream-with-indices-in-java-8?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa). You you need to work with indexes it is probably better to use an old forEach loop. Streams are not designed to support operations which involves indexes of the elements. – Anton Balaniuc May 21 '18 at 14:31

1 Answers1

4

Use Collectors.toMap on a Stream<Integer> of the List's indices:

Map<Integer,String> listMap =
   IntStream.range(0,lists.size())
            .boxed()
            .collect(Collectors.toMap(Function.identity(),
                                      lists::get,
                                      (a,b)->a,
                                      LinkedHashMap::new));

P.S., the output Map is a Map<Integer,String>, which fits the for loop in your question (unlike the specified Map<Integer,List<String>>, which doesn't, unless you change the input List from List<String> to List<List<String>>).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Any reason you preferred `Function.identity()` over `Function::identity` ? – Mrinal May 21 '18 at 17:19
  • @mks What do you think is the target type of `Function::identity`? – Flown May 21 '18 at 18:06
  • @mks Function.identity() returns an identity Function (which can also be expressed by the lambda expression i-> i). That's what was needed for generating the keys of the output map. – Eran May 21 '18 at 18:14
  • My bad, I got confused with multiple parameters with real method call vs. method reference. – Mrinal May 21 '18 at 18:28