使用Stream而不是for循环创建增量int数组 [英] Create array of incremental int using Stream instead of for loop

查看:121
本文介绍了使用Stream而不是for循环创建增量int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个构建增量数字数组的函数.

I want to create a function that builds an array of incremental numbers.

例如,我想要获得类似的东西:

For example, I want to obtain something like:

int[] array = new int[]{1, 2, 3, 4, 5, 6, 7, 8, ..., 1000000};

该函数将接收两个参数:数组的起始编号(包括起始编号)和最终长度:

The function will receive two parameters: start number (inclusive) and the final length of the array:

public int[] buildIncrementalArray(int start, int length) { ... }

我知道如何使用for循环:

I know how to do it using a for loop:

public int[] buildIncrementalArray(int start, int length) {
    int[] result = new int[length];
    for(int i = 0 ; i < length ; i++) {
        result[i] = start + i;
    }
    return result;
}

我想使用Java 8 Stream API,而不是使用for循环.有人知道如何使用Stream API做到这一点吗?

Instead of using a for loop, I want to use Java 8 Stream API. Does anybody know how to do it using Stream API?

推荐答案

已经有一个内置方法:

int[] array = IntStream.range(start, start + length).toArray();

IntStream.range 以1的增量步长从开始(包括)到结束(不包括)返回顺序的有序IntStream.

如果要包含end元素,则可以使用

If you want to include the end element, you can use IntStream.rangeClosed.

这篇关于使用Stream而不是for循环创建增量int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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