javajava-streamdeclarative-programming

Populate list of multiples using stream


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;
}

Solution

  • 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());
    }