For loop - like Python range function

后端 未结 9 1515
情歌与酒
情歌与酒 2020-12-30 21:45

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]


        
相关标签:
9条回答
  • 2020-12-30 22:27

    What you can do to substitute the range in python in java can be done with the following code. NOTE: I am not going off of your code, I am just writing a small piece of code and showing it to you.

    in python you would do.. . .

    if -2 <= x <= 10:
         print(x) 
    

    in java you would substitute this range and do. . ..

    if(x >= -2 && x <= 10){
    System.out.println("x")
    }
    

    By doing the above code in java, you don't need a range, but you have the -2 <= x <=10 range and split it into x >= -2 and x <= 10. It means the same thing, but the one I explained in java may take the compiler a longer time to read. So if you are using python go with the former's code format, and if you are using java, use the latter's code format.

    0 讨论(0)
  • 2020-12-30 22:28

    If you really, really want to obtain an equivalent result in Java, you'll have to do some more work:

    public int[] range(int start, int end, int step) {
        int n = (int) Math.ceil((end-start)/(double)step);
        int[] arange = new int[n];
        for (int i = 0; i < n; i++)
            arange[i] = i*step+start;
        return arange;
    }
    

    Now range(0, 4, 1) will return the expected value, just like Python: [0, 1, 2, 3]. Sadly there isn't a simpler way in Java, it's not a very expressive language, like Python.

    0 讨论(0)
  • 2020-12-30 22:32

    As far as I know, there's not an equivalent function in java. But you can write it yourself:

    public static int[] range(int n) {
        int[] ans = new int[n];
        int i;
        for(i = 0; i < n; i++) {
            ans[i] = i;
        }
        return ans;
    }
    
    0 讨论(0)
  • 2020-12-30 22:37

    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

    0 讨论(0)
  • 2020-12-30 22:38

    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 .

    0 讨论(0)
  • 2020-12-30 22:40

    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);
    }
    
    0 讨论(0)
提交回复
热议问题