Java:是否等效于Python的range(int,int)?

问题:Java:是否等效于Python的range(int,int)?

Java是否具有等效于Python range(int, int)方法的方法?

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


回答 0

Guava还提供类似于Python的东西range

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

您也可以使用Guava的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;
  }
};

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;
  }
};

回答 1

旧问题,新答案(对于Java 8)

    IntStream.range(0, 10).forEach(
        n -> {
            System.out.println(n);
        }
    );

或带有方法引用:

IntStream.range(0, 10).forEach(System.out::println);

Old question, new answer (for Java 8)

    IntStream.range(0, 10).forEach(
        n -> {
            System.out.println(n);
        }
    );

or with method references:

IntStream.range(0, 10).forEach(System.out::println);

回答 2

从Guava 15.0开始,Range.asSet()已被弃用,并计划在版本16中删除。请改用以下命令:

ContiguousSet.create(Range.closed(1, 5), DiscreteDomain.integers());

Since Guava 15.0, Range.asSet() has been deprecated and is scheduled to be removed in version 16. Use the following instead:

ContiguousSet.create(Range.closed(1, 5), DiscreteDomain.integers());

回答 3

我正在研究一个名为Jools的 Java utils小库,它包含一个Range提供所需功能的类(有一个可下载的JAR)。
构造函数可以是Range(int stop)Range(int start, int stop)Range(int start, int stop, int step)(类似于for循环),您可以对其进行迭代(使用惰性求值),也可以使用其toList()方法显式获取范围列表。

for (int i : new Range(10)) {...} // i = 0,1,2,3,4,5,6,7,8,9

for (int i : new Range(4,10)) {...} // i = 4,5,6,7,8,9

for (int i : new Range(0,10,2)) {...} // i = 0,2,4,6,8

Range range = new Range(0,10,2);
range.toList(); // [0,2,4,6,8]

I’m working on a little Java utils library called Jools, and it contains a class Range which provides the functionality you need (there’s a downloadable JAR).
Constructors are either Range(int stop), Range(int start, int stop), or Range(int start, int stop, int step) (similiar to a for loop) and you can either iterate through it, which used lazy evaluation, or you can use its toList() method to explicitly get the range list.

for (int i : new Range(10)) {...} // i = 0,1,2,3,4,5,6,7,8,9

for (int i : new Range(4,10)) {...} // i = 4,5,6,7,8,9

for (int i : new Range(0,10,2)) {...} // i = 0,2,4,6,8

Range range = new Range(0,10,2);
range.toList(); // [0,2,4,6,8]

回答 4

public int[] range(int start, int stop)
{
   int[] result = new int[stop-start];

   for(int i=0;i<stop-start;i++)
      result[i] = start+i;

   return result;
}

原谅任何语法或样式错误;我通常使用C#编程。

public int[] range(int start, int stop)
{
   int[] result = new int[stop-start];

   for(int i=0;i<stop-start;i++)
      result[i] = start+i;

   return result;
}

Forgive any syntax or style errors; I normally program in C#.


回答 5

您可以使用以下代码段来获取一组整数范围:

    Set<Integer> iset = IntStream.rangeClosed(1, 5).boxed().collect
            (Collectors.toSet());

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());

回答 6

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;
}

(长回答只是说“不”)

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”)


回答 7

Java 9- IntStream::iterate

从Java 9开始,您可以使用IntStream::iterate,甚至可以自定义步骤。例如,如果要int数组:

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

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());
}

然后使用它:

int[] range = getInRange(0, 10, 1);

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);

回答 8

Groovy的漂亮的Range类可以从Java中使用,尽管它当然不是Groovy的。

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


回答 9

“ Functional Java”库允许以这种方式进行有限程度的编程,它具有创建fj.data.Array实例的range()方法。

看到:

同样,“完全懒惰”库提供了一种惰性范围方法:http : //code.google.com/p/totallylazy/

The “Functional Java” library allows to program in such a way to a limited degree, it has a range() method creating an fj.data.Array instance.

See:

Similarly the “Totally Lazy” library offers a lazy range method: http://code.google.com/p/totallylazy/


回答 10

如果您打算像在Python循环中那样使用它,则Java会使用for语句很好地循环,这使此结构不必要。

If you mean to use it like you would in a Python loop, Java loops nicely with the for statement, which renders this structure unnecessary for that purpose.


回答 11

IntStream.range(0, 10).boxed().collect(Collectors.toUnmodifiableList());
IntStream.range(0, 10).boxed().collect(Collectors.toUnmodifiableList());

回答 12

我知道这是一篇老文章,但是如果您正在寻找一种返回对象流并且不希望或不能使用任何其他依赖项的解决方案,请执行以下操作:

Stream.iterate(start, n -> n + 1).limit(stop);

开始 -包容性停止 – 包容性

I know this is an old post but if you are looking for a solution that returns an object stream and don’t want to or can’t use any additional dependencies:

Stream.iterate(start, n -> n + 1).limit(stop);

start – inclusive stop – exclusive