Listing Numbers Within a Range in Java – 在Java中列出一个范围内的数字

最后修改: 2019年 9月 8日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll explore different ways of listing sequences of numbers within a range.

在本教程中,我们将探讨在一个范围内列出数字序列的不同方法。

2. Listing Numbers in a Range

2.在一个范围内列出数字

2.1. Traditional for Loop

2.1.传统的for循环

We can use a traditional for loop to generate numbers in a specified range:

我们可以使用传统的for循环来生成指定范围内的数字。

public List<Integer> getNumbersInRange(int start, int end) {
    List<Integer> result = new ArrayList<>();
    for (int i = start; i < end; i++) {
        result.add(i);
    }
    return result;
}

The code above will generate a list containing numbers from start (inclusive) to end (exclusive).

上面的代码将生成一个包含从开始(包括)到结束(不包括)的数字的列表。

2.2. JDK 8 IntStream.range

2.2.JDK 8 IntStream.range

IntStream, introduced in JDK 8, can be used to generate numbers in a given range, alleviating the need for a for loop:

JDK 8中引入的IntStream可以用来生成给定范围内的数字,减轻了对for循环的需求。

public List<Integer> getNumbersUsingIntStreamRange(int start, int end) {
    return IntStream.range(start, end)
      .boxed()
      .collect(Collectors.toList());
}

2.3. IntStream.rangeClosed

2.3.IntStream.rangeClosed

In the previous section, the end is exclusive. To get numbers in a range where the end is inclusive, there’s IntStream.rangeClosed:

在上一节中,end是独占的。为了获得end是包容的范围内的数字,有IntStream.rangeClosed

public List<Integer> getNumbersUsingIntStreamRangeClosed(int start, int end) {
    return IntStream.rangeClosed(start, end)
      .boxed()
      .collect(Collectors.toList());
}

2.4. IntStream.iterate

2.4.IntStream.iterate

The previous sections used a range to get a sequence of numbers. When we know how many numbers in a sequence is needed, we can utilize the IntStream.iterate:

前面的章节使用了一个范围来获得一个数字序列。当我们知道需要一个序列中的多少个数字时,我们可以利用IntStream.iterate

public List<Integer> getNumbersUsingIntStreamIterate(int start, int limit) {
    return IntStream.iterate(start, i -> i + 1)
      .limit(limit)
      .boxed()
      .collect(Collectors.toList());
}

Here, the limit parameter limits the number of elements to iterate over.

这里,limit参数限制了要迭代的元素数量。

3. Conclusion

3.结论

In this article, we saw different ways of generating numbers within a range.

在这篇文章中,我们看到了在一个范围内生成数字的不同方法。

Code snippets, as always, can be found over on GitHub.

像往常一样,可以在GitHub上找到代码片段