How can I generate a list or array of sequential integers in Java?

BeeOnRope picture BeeOnRope · Apr 20, 2012 · Viewed 111.7k times · Source

Is there a short and sweet way to generate a List<Integer>, or perhaps an Integer[] or int[], with sequential values from some start value to an end value?

That is, something shorter than, but equivalent to1 the following:

void List<Integer> makeSequence(int begin, int end) {
  List<Integer> ret = new ArrayList<>(end - begin + 1);
  for (int i=begin; i<=end; i++) {
    ret.add(i);
  }
  return ret;  
}

The use of guava is fine.

Update:

Performance Analysis

Since this question has received several good answers, both using native Java 8 and third party libraries, I thought I'd test the performance of all the solutions.

The first test simply tests creating a list of 10 elements [1..10] using the following methods:

  • classicArrayList: the code given above in my question (and essentially the same as adarshr's answer).
  • eclipseCollections: the code given in Donald's answer below using Eclipse Collections 8.0.
  • guavaRange: the code given in daveb's answer below. Technically, this doesn't create a List<Integer> but rather a ContiguousSet<Integer> - but since it implements Iterable<Integer> in-order, it mostly works for my purposes.
  • intStreamRange: the code given in Vladimir's answer below, which uses IntStream.rangeClosed() - which was introduced in Java 8.
  • streamIterate: the code given in Catalin's answer below which also uses IntStream functionality introduced in Java 8.

Here are the results in kilo-operations per second (higher numbers are better), for all the above with lists of size 10:

List creation throughput

... and again for lists of size 10,000:

enter image description here

That last chart is correct - the solutions other than Eclipse and Guava are too slow to even get a single pixel bar! The fast solutions are 10,000 to 20,000 times faster than the rest.

What's going on here, of course, is that the guava and eclipse solutions don't actually materialize any kind of 10,000 element list - they are simply fixed-size wrappers around the start and endpoints. Each element is created as needed during iteration. Since we don't actually iterate in this test, the cost is deferred. All of the other solutions actually materialize the full list in memory and pay a heavy price in a creation-only benchmark.

Let's do something a bit more realistic and also iterate over all the integers, summing them. So in the case of the IntStream.rangeClosed variant, the benchmark looks like:

@Benchmark
public int intStreamRange() {
    List<Integer> ret = IntStream.rangeClosed(begin, end).boxed().collect(Collectors.toList());  

    int total = 0;
    for (int i : ret) {
        total += i;
    }
    return total;  
}

Here, the pictures changes a lot, although the non-materializing solutions are still the fastest. Here's length=10:

List<Integer> Iteration (length=10)

... and length = 10,000:

List<Integer> Iteration (length=10,000)

The long iteration over many elements evens things up a lot, but eclipse and guava remain more than twice as fast even on the 10,000 element test.

So if you really want a List<Integer>, eclipse collections seems like the best choice - but of course if you use streams in a more native way (e.g., forgetting .boxed() and doing a reduction in the primitive domain) you'll probably end up faster than all these variants.


1 Perhaps with the exception of error handling, e.g., if end < begin, or if the size exceeds some implementation or JVM limits (e.g., arrays larger than 2^31-1.

Answer

Vladimir Matveev picture Vladimir Matveev · Apr 3, 2014

With Java 8 it is so simple so it doesn't even need separate method anymore:

List<Integer> range = IntStream.rangeClosed(start, end)
    .boxed().collect(Collectors.toList());