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

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

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

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

    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.

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

    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]
    
    0 讨论(0)
  • 2020-12-02 08:50
    IntStream.range(0, 10).boxed().collect(Collectors.toUnmodifiableList());
    
    0 讨论(0)
  • 2020-12-02 08:50

    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

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

    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);
    
    0 讨论(0)
  • 2020-12-02 08:55

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