0

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;
}
Naman
  • 27,789
  • 26
  • 218
  • 353

2 Answers2

2

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());
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28
1

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());
}
Naman
  • 27,789
  • 26
  • 218
  • 353