Introduction
How do I write a public static range method or Range Class in Java 6 so that it at least encompasses common functions implemented in other programming languages?
If you want to answer a question, you can simply ignore the following.
ABOUT
From time to time, I miss the functionality that other languages have. I seem to have a different coding style for any language I write, and I don't want to change this habit. Therefore, if I want to reuse an algorithm that I wrote in another language, then I have to do annoying little hacks or workarounds to cover the missing functionality. I would like to find a permanent and effective fix for range().
For me, the method range()returns an input range, perhaps in a lazy way and has default values. At any moment, he has a beginning, an end condition, and a way to get the next element. It should work perfectly in for each cycle , as well as outside of it.
Notes
- , Google Guava . , , , JDK .

, :
- by
How to write - , . loop code,- : P
, , , , BigInteger Joda DateTime.
for-each- generic, typafe
- ables , :.cycle(),.filter(),.all(),.any(), transform()
range() :
public static <T extends Comparable<T>> Iterable<T>
range(T from, Predicate<T> to, Function<T, T> fNext)
throws NullPointerException, IllegalArgumentException {
, Range Builder.
Scala, Python 3, Groovy, .Net ( linq) [#, f #, vb ++], ruby , PHP... .
, ( ).
public static <T extends Comparable<T>> Iterable<T>
range(T from, Predicate<T> to, Function<T, T> fNext)
throws NullPointerException {
Preconditions.checkNotNull(from);
Preconditions.checkNotNull(to);
Preconditions.checkNotNull(fNext);
T current = from;
ArrayList<T> result = Lists.newArrayList();
if (to.apply(current)) result.add(current);
while (to.apply(current = Preconditions.checkNotNull(fNext.apply(current))))
result.add(current);
return result;
}
public static <T extends Comparable<T>> Iterator<T>
range2(final T from, final Predicate<T> to, final Function<T, T> fNext)
throws NullPointerException, UnsupportedOperationException {
Preconditions.checkNotNull(from);
Preconditions.checkNotNull(to);
Preconditions.checkNotNull(fNext);
return new Iterator<T>() {
T current = from;
@Override public boolean hasNext() {return to.apply(current);}
@Override public T next() {return current = Preconditions.checkNotNull(fNext.apply(current));}
@Override public void remove() {throw new UnsupportedOperationException();}
};
}