前言:

Java中,IntStream是一个接口,继承BaseStream。


里面有很多方法,如:filter()、map()、sorted()、empty()等,

下面,介绍一下它的一个常用静态方法:range() 方法。

源码:

 /**
     * Returns a sequential ordered {@code IntStream} from {@code startInclusive}
     * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of
     * {@code 1}.
     *
     * @apiNote
     * <p>An equivalent sequence of increasing values can be produced
     * sequentially using a {@code for} loop as follows:
     * <pre>{@code
     *     for (int i = startInclusive; i < endExclusive ; i++) { ... }
     * }</pre>
     *
     * @param startInclusive the (inclusive) initial value
     * @param endExclusive the exclusive upper bound
     * @return a sequential {@code IntStream} for the range of {@code int}
     *         elements
     */
    public static IntStream range(int startInclusive, int endExclusive) {
        if (startInclusive >= endExclusive) {
            return empty();
        } else {
            return StreamSupport.intStream(
                    new Streams.RangeIntSpliterator(startInclusive, endExclusive, false), false);
        }
    }

说明:

  • range()方法,创建一个以1为增量步长,从startInclusive(包括)到endExclusive(不包括)的有序的数字流。
  • 产生的IntStream对象,可以像数组一样遍历。

用法:

static IntStream range(int startInclusive,int endExclusive);

参数

  • IntStream : 原始整数值元素的序列
  • startInclusive : 规定了数字的起始值,包括
  • endExclusive : 规定了数字的上限值,不包括

返回值
    一个int元素范围的顺序IntStream

导包

    要使用Java中的IntStream类,请导入以下包:

import java.util.stream.IntStream;

举例:

class RangeTest {
    public static void main(String[] args) {
        /*
         * Creating an IntStream:
         *    --including the lower bound but
         *    --excluding the upper bound
         */
        IntStream intStream = IntStream.range(1,5);

        // Displaying the elements in range
        intStream.forEach(System.out::println);

        //上述代码简要写法
//      IntStream.range(1,5).forEach(i-> System.out.println(i));//创建一个1-4的数字流,并打印
    }
}

运行结果:

扩展:

如果想要数字是闭区间,可以使用 rangeClosed() 方法

static IntStream rangeClosed(int startInclusive, int endInclusive)

此方法和range的使用一模一样,唯一的区别是endInclusive参数是包含的

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐