使用流将元素插入到地图中

时间:2018-05-21 13:54:27

标签: java arrays hashmap java-stream

我有一个

List<String> lists;

我需要遍历此列表并输入LinkedHashMap。通常我会这样做:

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

如何使用流进行上述操作?

1 个答案:

答案 0 :(得分:4)

Collectors.toMap的{​​{1}}个索引上使用Stream<Integer>

List

PS,输出Map<Integer,String> listMap = IntStream.range(0,lists.size()) .boxed() .collect(Collectors.toMap(Function.identity(), lists::get, (a,b)->a, LinkedHashMap::new)); Map,它适合您问题中的for循环(与指定的Map<Integer,String>不同,除非您更改输入{{ 1}}从Map<Integer,List<String>>List)。

相关问题