gpt4 book ai didi

java - 使用流将元素插入 map

转载 作者:行者123 更新时间:2023-11-29 08:28:25 25 4
gpt4 key购买 nike

我有一个

List<String> lists;

我需要遍历这个列表并放入 LinkedHashMap。通常我这样做如下:

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

如何对流进行上述操作?

最佳答案

使用 Collectors.toMapStream<Integer> 上的 List的指标:

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

P.S.,输出 MapMap<Integer,String> ,它适合您问题中的 for 循环(与指定的 Map<Integer,List<String>> 不同,后者不适合,除非您将输入 ListList<String> 更改为 List<List<String>>)。

关于java - 使用流将元素插入 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50450471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com