gpt4 book ai didi

java - 使用 java 流将 String[] str = {"a","b","c","d","e","f"} 映射为 {a=b, c=d, e=f}

转载 作者:行者123 更新时间:2023-12-02 06:10:52 25 4
gpt4 key购买 nike

我有下面的代码来实现需求,但无法使用stream解决,我不知道如何在管道中增加i

String[] str = {"a","b","c","d","e","f"};
Map<String, String> strMap = new HashMap<>();
int i = 0;
while(i< str.length && i +1 < str.length) {
strMap.put(str[i],str[i+1]);
i +=2;
}

最佳答案

您无法使用简单的 str 流来完成此操作,但您可以使用索引流来模拟循环:

Map<String, String> strMap = IntStream.range(0, str.length - 1)
.filter(i -> i % 2 == 0)
.boxed()
.collect(Collectors.toMap(i -> str[i], i -> str[i + 1]));

关于java - 使用 java 流将 String[] str = {"a","b","c","d","e","f"} 映射为 {a=b, c=d, e=f},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46780944/

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