简体   繁体   English

使用流填充倍数列表

[英]Populate list of multiples using stream

Is there a way to write this method in a Java 8 declarative style, using stream()?有没有办法使用 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;
}

There are many ways to achieve what you want, one of them is using Intstream#iterate :有很多方法可以实现你想要的,其中之一是使用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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM