我想创建一个整数序列,最好是一个 IntStream
,它遵循一定的条件。一些简单的例子来解释我想要做什么:
从 0 开始的前 10 个偶数的序列(这里我没有问题,我用下面的代码片段来做)
IntStream.iterate(0, i -> i + 2).limit(10);
//0,2,4,6,8,10,12,14,16,18
前 10 个数字从 0 开始的序列,交替添加 2 和 3 到原始数字;所需的输出: //0,2,5,7,10,12,15,17,20,22
我也很想在这个场景中使用 IntStream.iterate()
或 IntStream.generate()
,但我自己无法做到。我正在使用经典的 for 循环,它可以工作,但对于这样一个相对简单的任务来说有点长List<Integer> list = new ArrayList<>();
list.add(0);
for(int i = 1, j = 1; i < 10; i++, j *= -1){
if(j > 0){
list.add(list.get(i-1) + 2);
}
else{
list.add(list.get(i-1) + 3);
}
}
//and then stream over the list to get IntStream
list.stream().mapToInt(Integer::intValue);
使用 IntStream.iterate()
或 IntStream.generate()
实现与上述相同的任何简单方法?对于三个或更多交替值,我不知道如何优雅地做到这一点。例如,如果我想通过将 +2、+5 和 +7 交替添加到具有所需输出的前一个数字来创建从 0 开始的前 10 个数字的序列:
//0,2,7,14,16,21,28,30,35,42
我曾考虑在具有 3 个 if-else 块或 switch case 的 for 循环中使用 i%3
,但是当我需要更多交替值并且我必须添加更多 ifs
或 cases
时,这会增长。任何想法如何做到这一点?如果您认为 IntStream.iterate()
或 IntStream.generate()
不是解决所描述任务的正确方法,我也愿意接受其他方法。
最佳答案
你可以从数学上看这个。假设您要交替添加 x1、x2、x3 ... xn。
前 n 项可以写成:
(0 * sum of all x's)
(0 * sum of all x's + x1)
(0 * sum of all x's + x1 + x2)
(0 * sum of all x's + x1 + x2 + x3)
...
(0 * sum of all x's + sum of all x's - xn)
接下来的 n 项可以用相同的方式编写,只是您将所有 0 替换为 1。(1 * sum of all x's)
(1 * sum of all x's + x1)
(1 * sum of all x's + x1 + x2)
(1 * sum of all x's + x1 + x2 + x3)
...
(1 * sum of all x's + sum of all x's - xn)
接下来的 n 项将所有 1 替换为 2,依此类推。所以我们只需要生成流 (1, 2, 3, 4...) 和
flatMap
每个元素 i
到流(i * sum of all x's)
(i * sum of all x's + x1)
(i * sum of all x's + x1 + x2)
(i * sum of all x's + x1 + x2 + x3)
...
(i * sum of all x's + sum of all x's - xn)
使用此模式,您可以像这样编写 2、5、7 流:final int a = 2,
final int b = 5,
final int c = 7;
final int sum = a + b + c;
IntStream.iterate(0, i -> i + 1).flatMap(
i -> IntStream.of(i * sum, i * sum + a, i * sum + a + b)
).limit(10);
如果您想改为执行 2,3,5,7:final int a = 2,
final int b = 3,
final int c = 5;
final int d = 7;
final int sum = a + b + c + d;
IntStream.iterate(0, i -> i + 1).flatMap(
i -> IntStream.of(i * sum, i * sum + a, i * sum + a + b, i * sum + a + b + c)
).limit(10);
我会让你把它推广到任何 int[]
数字。
关于java - IntStream.iterate 与要添加的交替值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67635316/