one.xingyi.fp.ListComprehensionsForExceptions Maven / Gradle / Ivy
package one.xingyi.fp;
import lombok.var;
import one.xingyi.interfaces.BiFunctionWithException;
import one.xingyi.interfaces.ConsumerWithException;
import one.xingyi.interfaces.FunctionWithException;
import java.io.IOException;
import java.util.*;
public interface ListComprehensionsForExceptions {
static List mapE(Iterable iterable, FunctionWithException fn) throws Exception {
List result = new ArrayList<>();
for (T t : iterable) result.add(fn.apply(t));
return result;
}
static List filterE(Iterable iterable, FunctionWithException filter) throws Exception {
List result = new ArrayList<>();
for (T t : iterable) if (filter.apply(t)) result.add(t);
return result;
}
static List collectE(Iterable iterable, FunctionWithException filter, FunctionWithException fn) throws Exception {
List result = new ArrayList<>();
for (T t : iterable) if (filter.apply(t)) result.add(fn.apply(t));
return result;
}
static List collectByClassE(Iterable iterable, Class theClass, FunctionWithException fn) throws Exception {
List result = new ArrayList<>();
for (T t : iterable) if (theClass.isInstance(t)) result.add(fn.apply(t));
return result;
}
static void foreachE(Iterable iterable, ConsumerWithException fn) throws Exception {
for (T t : iterable) fn.accept(t);
}
static List flatMapE(Iterable iterable, FunctionWithException> fn) throws Exception {
List result = new ArrayList<>();
for (T t : iterable) result.addAll(fn.apply(t));
return result;
}
static Map toIdMapE(Iterable iterable, FunctionWithException fn) throws Exception {
Map result = new HashMap<>();
for (T t : iterable) result.put(fn.apply(t), t);
return result;
}
static Map toMapE(Iterable iterable, FunctionWithException keyFn, FunctionWithException vFn) throws Exception {
Map result = new HashMap<>();
for (T t : iterable) result.put(keyFn.apply(t), vFn.apply(t));
return result;
}
static Acc foldE(Iterable iterable, BiFunctionWithException foldFn, Acc zero) throws Exception {
var result = zero;
for (T t : iterable)
result = foldFn.apply(result, t);
return result;
}
static T reduceE(Iterable iterable, BiFunctionWithException foldFn) throws Exception {
var iterator = iterable.iterator();
if (!iterator.hasNext()) throw new IllegalArgumentException("reduceE has been called with an empty list");
var result = iterator.next();
while (iterator.hasNext())
result = foldFn.apply(result, iterator.next());
return result;
}
}