Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop - like Python range function

I was wondering if in Java there is a function like the python range function.

range(4)

and it would return

[0,1,2,3]

This was an easy way to make for enhanced loops. It would be great to do this in Java because it would make for loops a lot easier. Is this possible?

like image 862
Kacper Lubisz Avatar asked May 15 '13 16:05

Kacper Lubisz


People also ask

Can we use range in for loop?

We can use a range() to simplify writing a for loop. The stop value of the range() must be specified, but we can also modify the start ing value and the step between integers in the range() .

What can be used instead of range in python?

range() vs xrange() in Python. The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python.

Can we use range in while loop in python?

Simply we can use while and range() function in python.

What is the purpose of range function in for loop in python?

The range() function is used to generate a sequence of numbers. Python range() function for loop is commonly used hence, knowledge of same is the key aspect when dealing with any kind of Python code. The most common use of range() function in Python is to iterate sequence type (Python range() List, string, etc. )


4 Answers

Java 8 (2014) has added IntStream (similar to apache commons IntRange), so you don't need external lib now.

import java.util.stream.IntStream;   IntStream.range(0, 3).forEachOrdered(n -> {     System.out.println(n); }); 

forEach can be used in place of forEachOrdered too if order is not important.

IntStream.range(0, 3).parallel() can be used for loops to run in parallel

like image 59
zengr Avatar answered Sep 19 '22 01:09

zengr


Without an external library, you can do the following. It will consume significantly less memory for big ranges than the current accepted answer, as there is no array created.

Have a class like this:

class Range implements Iterable<Integer> {      private int limit;      public Range(int limit) {         this.limit = limit;     }      @Override     public Iterator<Integer> iterator() {         final int max = limit;         return new Iterator<Integer>() {              private int current = 0;              @Override             public boolean hasNext() {                 return current < max;             }              @Override             public Integer next() {                 if (hasNext()) {                     return current++;                    } else {                     throw new NoSuchElementException("Range reached the end");                 }             }              @Override             public void remove() {                 throw new UnsupportedOperationException("Can't remove values from a Range");             }         };     } } 

and you can simply use it like this:

    for (int i : new Range(5)) {         System.out.println(i);     } 

you can even reuse it:

    Range range5 = new Range(5);      for (int i : range5) {         System.out.println(i);     }     for (int i : range5) {         System.out.println(i);     } 

As Henry Keiter pointed out in the comment below, we could add following method to the Range class (or anywhere else):

public static Range range(int max) {     return new Range(max); } 

and then, in the other classes we can

import static package.name.Range.range; 

and simply call

for (int i : range(5)) {     System.out.println(i); } 
like image 28
jlordo Avatar answered Sep 20 '22 01:09

jlordo


Um... for (int i = 0; i < k; i++)? You don't have to write enhanced for loops all day, you know, although they are cool...

And just for the sake of argument:

for (int i : range(k)) char count: 22

for (int i = 0; i < k; i++) char count: 27

Discounting the implementation of range, it is pseudo even.

like image 23
zw324 Avatar answered Sep 23 '22 01:09

zw324


Use Apache Commons Lang:

new IntRange(0, 3).toArray();

I wouldn't normally advocate introducing external libraries for something so simple, but Apache Commons are so widely used that you probably already have it in your project!

Edit: I know its not necessarily as simple or fast as a for loop, but its a nice bit of syntactic sugar that makes the intent clear.

Edit: See @zengr's answer using IntStream in Java 8 .

like image 24
Zutty Avatar answered Sep 22 '22 01:09

Zutty