es.usc.citius.hipster.util.F Maven / Gradle / Ivy
package es.usc.citius.hipster.util;
import java.util.Iterator;
/**
* This class contains a very limited set of functions to process iterables and iterators in a lazy way.
* Guava / Java 8 is not an option due to current size / compatibility restrictions.
* Required since the removal of Guava dependencies (issue #125 https://github.com/citiususc/hipster/issues/125)
* NOTE: This class may be removed in future versions to take advantage of Java 8 functional Streams
*
* Pure functional programmers, please forgive us for this crime
*
* @author Pablo Rodríguez Mier
*/
public final class F {
private F() {}
public static Iterable map(final Iterable it, final Function super T,? extends E> mapf){
return new Iterable() {
@Override
public Iterator iterator() {
return map(it.iterator(), mapf);
}
};
}
public static Iterator map(final Iterator it, final Function super T,? extends E> mapf){
return new Iterators.AbstractIterator() {
@Override
protected E computeNext() {
if (it.hasNext()){
return mapf.apply(it.next());
}
return null;
}
};
}
public static Iterable filter(final Iterable it, final Function super T, Boolean> condition) {
return new Iterable() {
@Override
public Iterator iterator() {
return filter(it.iterator(), condition);
}
};
}
public static Iterator filter(final Iterator it, final Function super T, Boolean> condition) {
return new Iterators.AbstractIterator() {
@Override
protected T computeNext() {
while(it.hasNext()){
T next = it.next();
if (condition.apply(next)){
return next;
}
}
return null;
}
};
}
public static Iterable flatMap(final Iterable it, final Function super E, ? extends Iterable extends T>> mapf){
return new Iterable() {
@Override
public Iterator iterator() {
return flatMap(it.iterator(), new Function>() {
@Override
public Iterator extends T> apply(E input) {
return mapf.apply(input).iterator();
}
});
}
};
}
public static Iterator flatMap(final Iterator it, final Function super E, ? extends Iterator extends T>> mapf){
return new Iterators.AbstractIterator() {
Iterator> mapIt = map(it, mapf);
Iterator extends T> current = mapIt.hasNext() ? mapIt.next() : Iterators.empty();
@Override
protected T computeNext() {
if (current.hasNext()) return current.next();
if (mapIt.hasNext()){
current = mapIt.next();
return computeNext();
}
return null;
}
};
}
}