Shortest way to get an Iterator over a range of Integers in Java

后端 未结 7 2003
时光说笑
时光说笑 2020-12-29 22:27

What\'s the shortest way to get an Iterator over a range of Integers in Java? In other words, implement the following:

/** 
* Returns an Iterator over the in         


        
7条回答
  •  情深已故
    2020-12-29 22:57

    A sample using stream API in java 8:

    int first = 0;
    int count = 10;
    Iterator it = IntStream.range(first, first + count).iterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
    

    Without iterator, it could be:

    int first = 0;
    int count = 10;
    IntStream.range(first, first + count).forEach(i -> System.out.println(i));
    

提交回复
热议问题