I'll have two integers and will want to generate an array of those two numbers and all the numbers in between as strings (I know the ranges are small).

i.e. given 1004 and 1008. I'd generate "1004", "1005", "1006", "1007", "1008"

I'm familiar with C# and there I'd do something like

var start = 1004;
var end = 1008;
var fullRange = Enumerable.Range(start, end - start + 1)
                          .Select(i => i.ToString())

I need to do this in Java 8 and have come up with

 String[] fullRange = IntStream.range(start, end+1)

But I'm new to Java and wondered if there's a better / more-readable way to achieve this in Java. Am I just cramming C# into Java?


2 Answers 2


Can you use a stream rather than an array in the rest of your application? If so I'd simply cut off the toArray bit at the end. Otherwise this looks exactly like what I'd expect in Java 8.

  • \$\begingroup\$ I could possibly use a stream. The consumer of this output runs over the range to create a map. Presumably then passing a Stream around is like passing IEnumerable in C#. \$\endgroup\$ Jun 10, 2017 at 18:24
  • 1
    \$\begingroup\$ @PaulD'Ambra - Approximately, although note that an IEnumerable can be consumed multiple times but a Stream can only be consumed once. Java's closest equivalent to IEnumerable is probably Iterable, but you'd have to provide a custom implementation to achieve that in this case. IMO this is one of the areas where the CLR's design is much better than Java's. \$\endgroup\$
    – Jules
    Jun 11, 2017 at 2:22

IntStream has a rangeClosed method that allows you to omit the +1.

IntStream.rangeClosed(start, end) instead of IntStream.range(start, end+1)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.