gpt4 book ai didi

java - 使用流填充倍数列表

转载 作者:行者123 更新时间:2023-12-01 16:42:23 25 4
gpt4 key购买 nike

有没有办法使用stream()以Java 8声明式风格编写此方法?

public List<Integer> getFives(int numberOfElements, int incrementNum) {
List<Integer> list;
int value = incrementNum;
list.add(value);
for (int i = 0; i < numberOfElements; i++) {
value = value + incrementNum;
list.add(value);
}
return list;
}

最佳答案

有很多方法可以实现您想要的目标,其中之一是使用 Intstream#iterate :

public static  List<Integer> getFives(int numberOfElements, int incrementNum) {    
return IntStream.iterate(incrementNum, i -> i+incrementNum)
.limit(numberOfElements)
.boxed()
.collect(Collectors.toList());
}

关于java - 使用流填充倍数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60864903/

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