Reputation: 129
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?
Upvotes: 2
Views: 3299
Reputation: 393811
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>>
).
Upvotes: 5