Java 8是否提供了重复值或函数的好方法? [英] Does Java 8 provide a good way to repeat a value or function?
问题描述
在许多其他语言中,例如。 Haskell,很容易多次重复一个值或函数,例如。获得价值1的8份副本清单:
In many other languages, eg. Haskell, it is easy to repeat a value or function multiple times, eg. to get a list of 8 copies of the value 1:
take 8 (repeat 1)
但是我还没有在Java 8中找到它。在Java 8的JDK中是否有这样的功能?
but I haven't found this yet in Java 8. Is there such a function in Java 8's JDK?
或者相当于一个范围的东西,比如
Or alternatively something equivalent to a range like
[1..8]
这似乎是Java中一个冗长语句的明显替代品,如
It would seem an obvious replacement for a verbose statement in Java like
for (int i = 1; i <= 8; i++) {
System.out.println(i);
}
有类似的东西
Range.from(1, 8).forEach(i -> System.out.println(i))
虽然这个特殊的例子实际上看起来并不简洁......但希望它更具可读性。
though this particular example doesn't look much more concise actually... but hopefully it's more readable.
推荐答案
对于这个具体的例子,你可以这样做:
For this specific example, you could do:
IntStream.rangeClosed(1, 8)
.forEach(System.out::println);
如果您需要一个不同于1的步骤,您可以使用映射功能,例如,步骤2:
If you need a step different from 1, you can use a mapping function, for example, for a step of 2:
IntStream.rangeClosed(1, 8)
.map(i -> 2 * i - 1)
.forEach(System.out::println);
或者构建自定义迭代并限制迭代的大小:
Or build a custom iteration and limit the size of the iteration:
IntStream.iterate(1, i -> i + 2)
.limit(8)
.forEach(System.out::println);
这篇关于Java 8是否提供了重复值或函数的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!