Java 8 是否提供了一种重复值或函数的好方法? [英] Does Java 8 provide a good way to repeat a value or function?

查看:18
本文介绍了Java 8 是否提供了一种重复值或函数的好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多其他语言中,例如.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆