streams - Ranges of int

本文通过实例展示了Java 8中IntStream类的range方法使用,包括如何生成整数序列并进行求和操作,以及如何重复执行特定次数的操作。同时,对比了传统for循环、增强for循环和Stream API的不同实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The IntStream(since 1.8) class provides a range() method to produce a stream that is a sequence of int s.

case 1:

// streams/Ranges.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import static java.util.stream.IntStream.*;

public class Ranges {
  public static void main(String[] args) {
    // The traditional way:
    int result = 0;
    for (int i = 10; i < 20; i++) {
      result += i;
    }
    System.out.println(result);

    // for-in with a range:
    result = 0;
    for (int i : range(10, 20).toArray()) {
      result += i;
    }
    System.out.println(result);

    // Use streams:
    System.out.println(range(10, 20).sum());
  }
}
/* Output:
145
145
145
*/

case 2:

// onjava/Repeat.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package onjava;

import static java.util.stream.IntStream.*;

public class Repeat {
  public static void repeat(int n, Runnable action) {
    range(0, n).forEach(i -> action.run());
  }
}
// streams/Looping.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import static onjava.Repeat.*;

public class Looping {
  static void hi() {
    System.out.println("Hi!");
  }

  public static void main(String[] args) {
    repeat(3, () -> System.out.println("Looping!"));
    // repeat(3, System.out::println);
    repeat(2, Looping::hi);
  }
}
/* Output:
Looping!
Looping!
Looping!
Hi!
Hi!
*/

Note that IntStream.range() is more limited than onjava.Range.range() . Because of its optional third step argument, the latter has the ability to generate ranges that step by more than one, and that can count down from a higher value to a lower one.

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Ranges.java

3. https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#range-int-int-

4. https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#toArray--

5. https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#sum--

6. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/onjava/Repeat.java

7. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Looping.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值