Explain Codes LogoExplain Codes Logo

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

java
stream-engineering
java-8
performance
Alex KataevbyAlex Kataev·Feb 10, 2025
TLDR

You can generate a sequence of numbers using IntStream.range (end exclusive) and IntStream.rangeClosed (end inclusive):

For a List<Integer>:

List<Integer> list = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList());

For arrays:

int[] array = IntStream.range(1, 11).toArray();

And for Java 16 or later users, a more streamlined conversion is possible:

List<Integer> list = IntStream.rangeClosed(1, 10).boxed().toList();

Importantly, ensure you handle edge cases where the upper boundary is lesser than the lower one and beware of sizes exceeding the JVM constraints.

Harnessing the power of streams

Transforming Streams

You can convert streams to sets, lists, or bags using libraries like Guava and Eclipse Collections. Here's two sample conversions:

// Guava Set<Integer> set = ContiguousSet.create(Range.closed(1, 10), DiscreteDomain.integers()); // Eclipse Collections IntList list = IntInterval.oneTo(10).toList();

These libraries also offer efficient handling of large integer lists via non-materializing or lazy evaluations.

Error handling and cautionary tales

Prudence over Performance

While writing code, it's often tempting to use for-loops. However, when generating numbers, using streams could yield more performant results, especially with primitive collections that eliminate costly boxing and unboxing operations.

// Eclipse Collections can come to rescue here MutableIntList intList = IntLists.mutable.withAll(list);

Error preparedness

Error handling is an essential part of a robust solution. This isn't the most fun part of our job, but rules are rules folks! Ensure you handle invalid range cases and pay attention to constraints imposed by JVM or collection implementation.

Play with specialised integer sequences

Interoperability: From Sets to Arrays

You can go beyond lists and convert streams to arrays for easier accessibility:

// We love arrays! int[] array = IntStream.rangeClosed(1, 5).toArray();

Features such as direct access make arrays an attractive option in many scenarios.

The Simplicity Wedding: Streams meet Arrays

This example demonstrates gathering the elements of a stream into a list:

// It's as simple as 1-2-3...ha...get it? List<Integer> list = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.toList());

Choosing the right strategy for your Java version

Depending on your Java version, you might prefer specific methods. Here's a quick cheat sheet:

  • Java 8: Go for .boxed().collect(Collectors.toList()). Simple and clean!
  • Java 16+: Be succinct! Use .toList() after boxing your IntStream.
  • Performance considerations: Third-party libraries might offer optimizations that the Java standard library doesn't.