ru.yandex.bolts.function.Function Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of bolts Show documentation
Show all versions of bolts Show documentation
Collections utilities used in various Yandex projects
The newest version!
package ru.yandex.bolts.function;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import ru.yandex.bolts.collection.Cf;
import ru.yandex.bolts.collection.MapF;
import ru.yandex.bolts.function.forhuman.Comparator;
import ru.yandex.bolts.internal.ReflectionUtils;
import ru.yandex.bolts.internal.Validate;
@FunctionalInterface
public interface Function {
R apply(A a);
default Function andThen(final Function super R, ? extends C> g) {
return a -> g.apply(apply(a));
}
default Function1V andThen(final Function1V super R> g) {
return a -> g.apply(apply(a));
}
default Function1B andThen(final Function1B super R> g) {
return a -> g.apply(apply(a));
}
default Comparator andThen(final Comparator comparator) {
return (o1, o2) -> comparator.compare(apply(o1), apply(o2));
}
default Comparator andThen(final Function2I comparator) {
return (a, b) -> comparator.apply(apply(a), apply(b));
}
default Function1B andThenEquals(R value) {
return andThen(Function1B.equalsF(value));
}
@SuppressWarnings({"unchecked"})
default Comparator andThenNaturalComparator() {
return andThen((Comparator) Comparator.naturalComparator());
}
default Function compose(Function g) {
return g.andThen(this);
}
default Function0 bind(final A param) {
return () -> apply(param);
}
static Function2, A, Function0> bindF2() {
return Function::bind;
}
default Function> bindF() {
return Function.bindF2().bind1(this);
}
static Function2, A, R> applyF() {
return Function::apply;
}
@SuppressWarnings("unchecked")
default Function uncheckedCast() {
return (Function) this;
}
default Function1V ignoreResult() {
return this::apply;
}
default Function ignoreNullF() {
return a -> {
if (a == null) return null;
else return Function.this.apply(a);
};
}
static Function identityF() {
return a -> a;
}
static Function toStringF() {
return t -> t != null ? t.toString() : "null";
}
static Function constF(final B b) {
return a -> b;
}
@SuppressWarnings("unchecked")
static Function wrap(final Method method) {
if ((method.getModifiers() & Modifier.STATIC) != 0) {
Validate.isTrue(method.getParameterTypes().length == 1, "static method must have single argument, " + method);
return a -> (B) ReflectionUtils.invoke(method, null, a);
} else {
Validate.isTrue(method.getParameterTypes().length == 0, "instance method must have no arguments, " + method);
return a -> (B) ReflectionUtils.invoke(method, a);
}
}
default Function memoize() {
return new Function() {
private final MapF cache = Cf.hashMap();
public synchronized R apply(A a) {
return cache.getOrElseUpdate(a, Function.this);
}
};
}
} //~