Home Instant Tea How to Generate List from 1 to N in Java

How to Generate List from 1 to N in Java

Published: Last Updated on 0 comment

Hello Devs! Welcome to the Instant Tea section from CodersTea.in. Here I will directly jump to the solution i.e. “Show me the Code, Damn it”. If you need to know the code in more detail, then let me know in the comments. I will add the link to my (old or the one I will be writing) or other resources for you.

Let us quickly jump to the solution for the problem you asked 🤔

How to Generate List from 1 to N in Java

There are multiple ways to generate the list from 1 to N or M to N in Java. We will look at 3 with various versions of Java.

Using Simple For Loop

Just iterate from 1 to N in for a loop and add it to the list.

int n = 10;
List<Integer> list = new ArrayList<>(n);
// 1 to n (inclusive)
for (int i = 1; i <= n; i++) {
    list.add(i);
}Code language: Java (java)

Using IntStream – Java 8

Using IntStream‘s range for end exclusive and rangeClosed for end inclusive. Here is how.

int n = 10;
// 1 to 9 (n is excusive)
List<Integer> list = IntStream.range(1, n)
        .boxed()
        .collect(Collectors.toList());

// 1 to 10 (n inclusive)
List<Integer> list = IntStream.rangeClosed(1, n)
        .boxed()
        .collect(Collectors.toList());
Code language: Java (java)

Using IntStream – Java 16 and Above

with Java 16 you can remove the collect method from streaming and instead use toList it directly. here is the rewritten version of the above code.

int n = 10;
// 1 to 9 (n is excusive)
List<Integer> list = IntStream.range(1, n)
        .boxed()
        .toList();

// 1 to 10 (n inclusive)
List<Integer> list = IntStream.rangeClosed(1, n)
        .boxed()
        .toList();Code language: Java (java)

You can also read Stream API: The Hero Without a Cape and Functional Interfaces in Java to know more about Stream API

It’s Done, But one more thing You can Do 🫵

And yes, that’s your solution there. I hope this will work for you. Let me know in the comments if you have any other solution. See all other Instant Tea posts here. Before going, do connect with us on social media.  It’s @coderstea on TwitterLinkedinFacebookInstagram, and YouTube.

Also, please subscribe to our newsletter to know about the latest updates from CodersTea.

See you in the next post.

HAKUNA MATATA!!!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Ads
Ads
Ads

@2023 All Right Reserved. Designed and Developed by CodersTea

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More