Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java 8 range of numbers

farenda 2016-11-20 0

How to generate in Java 8 range of numbers? This is practical problem, often met when writing tests. In this post we’ll cover fast implementation, comfortable, and flexible with Java 8 Streams!

Traditional for-each loop

The simplest and fastest way to get range of numbers in given range is to use simple for-each loop:

List<Integer> forLoopRange(int from, int limit) {
    List<Integer> numbers = new ArrayList<>(limit);
    for (int to = from+limit; from < to; ++from) {
        numbers.add(from);
    }
    return numbers;
}

When we want to have a range of ints between 20 and 30 (exclusive) we can use it like that: forLoopRange(20, 10). It will produce:

[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Java 8 IntStream

Since Java 8 we can generate range of numbers using IntStream from java.util.stream package. It is slower, but more comfortable and speed not always is the most important factor:

List<Integer> streamRange(int from, int limit) {
    return IntStream.range(from, from+limit)
            .boxed()
            .collect(toList());
}

At the end we use Collectors.toList() to aggregate the numbers into a list, but equally well you could use Collectors.toSet(), because every number is different here anyway.

Let’s run it: streamRange(20, 10):

[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Note that the closing element is exclusive as usually in Java, when we operate on ranges: from – inclusive, to – exclusive.

Java 8 IntStream with closed range

In case you want to have inclusive range, IntStream has a special method for that purpose – IntStream.rangeClosed:

List<Integer> inclusiveRange(int from, int limit) {
    return IntStream.rangeClosed(from, from+limit)
            .boxed()
            .collect(toList());
}

Now the last number is included in range:

[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

Java 8 iterate range

A very interesting approach to generate range of numbers is IntStream.iterate(int seed, IntUnaryOperator f) method:

List<Integer> iterateStream(int from, int step, int limit) {
    return IntStream.iterate(from, i -> i+step) // next int
            .limit(limit/step) // only numbers in range
            .boxed()
            .collect(toList());
}

It allows to use a function that will produce the next number. In our case we want to take every step number, like here – iterateStream(20, 2, 10):

[20, 22, 24, 26, 28]

Very cool Java 8 feature! :-)

References:

  • Check out Java Util Tutorial for more Java 8 methods on Collections
Share with the World!
Categories Java Tags java, java-basics, java-util, java8
Previous: Java 8 count frequency of chars in String
Next: Java random integers in range

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored