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

后端 未结 7 2000
时光说笑
时光说笑 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:56

    An example using the guava framework. Note that this will not materialize the set (although you have to read the ContiguousSet implementation to verify that).

    import com.google.common.collect.ContiguousSet;
    import com.google.common.collect.DiscreteDomain;
    import com.google.common.collect.DiscreteDomains;
    
    class RangeIterator { 
    
        public Iterator range(int start, int length) {
            assert length > 0;
            Range dim_range = Ranges.closedOpen(start, start + length);
            DiscreteDomain ints = DiscreteDomains.integers();
            ContiguousSet dim = dim_range.asSet(ints);
            return dim.iterator();
        }
    }
    

提交回复
热议问题