Is there a way to write this method in a Java 8 declarative style, using stream()?
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;
}
There are many ways to achieve what you want, one of them is using Intstream#iterate
:
public static List<Integer> getFives(int numberOfElements, int incrementNum) {
return IntStream.iterate(incrementNum, i -> i+incrementNum)
.limit(numberOfElements)
.boxed()
.collect(Collectors.toList());
}
You seem to be looking for multiples as:
public List<Integer> getMultiples(int numberOfElements, int incrementNum) {
return IntStream.rangeClosed(1, numberOfElements)
.mapToObj(i -> i * incrementNum)
.collect(Collectors.toList());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.