com.slimgears.util.stream.Safe Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of stream-utils Show documentation
Show all versions of stream-utils Show documentation
General purpose utils / module: stream-utils
package com.slimgears.util.stream;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
@SuppressWarnings("WeakerAccess")
public class Safe {
public interface UnsafeSupplier {
T get() throws Exception;
}
public interface UnsafeConsumer {
void accept(T val) throws Exception;
}
public interface UnsafeRunnable {
void run() throws Exception;
}
public interface UnsafeFunction {
R apply(T from) throws Exception;
}
public interface Closeable extends AutoCloseable {
void close();
}
public static T safely(Callable callable) {
try {
return callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Supplier ofCallable(Callable callable) {
return () -> safely(callable);
}
public static Closeable ofClosable(AutoCloseable closeable) {
return ofRunnable(closeable::close)::run;
}
public static Supplier ofSupplier(UnsafeSupplier supplier) {
return () -> safely(supplier::get);
}
public static Runnable ofRunnable(UnsafeRunnable runnable) {
return () -> safely(() -> { runnable.run(); return null; });
}
public static Function ofFunction(UnsafeFunction function) {
return val -> safely(() -> function.apply(val));
}
public static Consumer ofConsumer(UnsafeConsumer consumer) {
return val -> safely(() -> { consumer.accept(val); return null; });
}
}