Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

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

2. Listing Numbers in a Range

2.1. Traditional for Loop

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

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

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

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

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:

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

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:

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.

3. Conclusion

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

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

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!