Java: Equivalent of Python's range(int, int)?

后端 未结 14 1818
北荒
北荒 2020-12-02 08:17

Does Java have an equivalent to Python\'s range(int, int) method?

相关标签:
14条回答
  • 2020-12-02 08:36

    Groovy's nifty Range class can be used from Java, though it's certainly not as groovy.

    0 讨论(0)
  • 2020-12-02 08:37

    Java 8

    private static int[] range(int start, int stop, int step) {
        int[] result = new int[(stop-start)%step == 0 ? (stop-start)/step : (stop-start)/step+1];
        int count = 0;
        Function<Integer, Boolean> condition = step > 0 ? (x) -> x < stop : (x) -> x > stop;
        for (int i = start; condition.apply(i); i += step) {
            result[count] = i;
            count++;
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-12-02 08:40

    You can use the following code snippet in order to get a range set of integers:

        Set<Integer> iset = IntStream.rangeClosed(1, 5).boxed().collect
                (Collectors.toSet());
    
    0 讨论(0)
  • 2020-12-02 08:42

    Guava also provides something similar to Python's range:

    Range.closed(1, 5).asSet(DiscreteDomains.integers());
    

    You can also implement a fairly simple iterator to do the same sort of thing using Guava's AbstractIterator:

    return new AbstractIterator<Integer>() {
      int next = getStart();
    
      @Override protected Integer computeNext() {
        if (isBeyondEnd(next)) {
          return endOfData();
        }
        Integer result = next;
        next = next + getStep();
        return result;
      }
    };
    
    0 讨论(0)
  • 2020-12-02 08:44

    Java 9 - IntStream::iterate

    Since Java 9 you can use IntStream::iterate and you can even customize the step. For example if you want int array :

    public static int[] getInRange(final int min, final int max, final int step) {
        return IntStream.iterate(min, i -> i < max, i -> i + step)
                .toArray();
    }
    

    or List :

    public static List<Integer> getInRange(final int min, final int max, final int step) {
        return IntStream.iterate(min, i -> i < max, i -> i + step)
                .boxed()
                .collect(Collectors.toList());
    }
    

    And then use it :

    int[] range = getInRange(0, 10, 1);
    
    0 讨论(0)
  • 2020-12-02 08:45
    public int[] range(int start, int length) {
        int[] range = new int[length - start + 1];
        for (int i = start; i <= length; i++) {
            range[i - start] = i;
        }
        return range;
    }
    

    (Long answer just to say "No")

    0 讨论(0)
提交回复
热议问题