Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.landawn.abacus.util.Fn Maven / Gradle / Ivy
Go to download
A general programming library in Java/Android. It's easy to learn and simple to use with concise and powerful APIs.
/*
* Copyright (c) 2017, Haiyang Li.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.landawn.abacus.util;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.AbstractCollection;
import java.util.AbstractList;
import java.util.AbstractMap;
import java.util.AbstractQueue;
import java.util.AbstractSet;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Deque;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import com.landawn.abacus.annotation.Beta;
import com.landawn.abacus.annotation.SequentialOnly;
import com.landawn.abacus.annotation.Stateful;
import com.landawn.abacus.annotation.SuppressFBWarnings;
import com.landawn.abacus.util.NoCachingNoUpdating.DisposableArray;
import com.landawn.abacus.util.NoCachingNoUpdating.DisposableObjArray;
import com.landawn.abacus.util.Tuple.Tuple1;
import com.landawn.abacus.util.Tuple.Tuple2;
import com.landawn.abacus.util.Tuple.Tuple3;
import com.landawn.abacus.util.Tuple.Tuple4;
import com.landawn.abacus.util.u.Optional;
import com.landawn.abacus.util.u.OptionalBoolean;
import com.landawn.abacus.util.u.OptionalByte;
import com.landawn.abacus.util.u.OptionalChar;
import com.landawn.abacus.util.u.OptionalDouble;
import com.landawn.abacus.util.u.OptionalFloat;
import com.landawn.abacus.util.u.OptionalInt;
import com.landawn.abacus.util.u.OptionalLong;
import com.landawn.abacus.util.u.OptionalShort;
import com.landawn.abacus.util.function.BiConsumer;
import com.landawn.abacus.util.function.BiFunction;
import com.landawn.abacus.util.function.BiPredicate;
import com.landawn.abacus.util.function.BinaryOperator;
import com.landawn.abacus.util.function.BooleanSupplier;
import com.landawn.abacus.util.function.ByteBiFunction;
import com.landawn.abacus.util.function.ByteBiPredicate;
import com.landawn.abacus.util.function.ByteBinaryOperator;
import com.landawn.abacus.util.function.ByteConsumer;
import com.landawn.abacus.util.function.ByteFunction;
import com.landawn.abacus.util.function.BytePredicate;
import com.landawn.abacus.util.function.Callable;
import com.landawn.abacus.util.function.CharBiFunction;
import com.landawn.abacus.util.function.CharBiPredicate;
import com.landawn.abacus.util.function.CharBinaryOperator;
import com.landawn.abacus.util.function.CharConsumer;
import com.landawn.abacus.util.function.CharFunction;
import com.landawn.abacus.util.function.CharPredicate;
import com.landawn.abacus.util.function.Consumer;
import com.landawn.abacus.util.function.DoubleBiFunction;
import com.landawn.abacus.util.function.DoubleBiPredicate;
import com.landawn.abacus.util.function.DoubleBinaryOperator;
import com.landawn.abacus.util.function.DoubleConsumer;
import com.landawn.abacus.util.function.DoubleFunction;
import com.landawn.abacus.util.function.DoublePredicate;
import com.landawn.abacus.util.function.FloatBiFunction;
import com.landawn.abacus.util.function.FloatBiPredicate;
import com.landawn.abacus.util.function.FloatBinaryOperator;
import com.landawn.abacus.util.function.FloatConsumer;
import com.landawn.abacus.util.function.FloatFunction;
import com.landawn.abacus.util.function.FloatPredicate;
import com.landawn.abacus.util.function.Function;
import com.landawn.abacus.util.function.IntBiFunction;
import com.landawn.abacus.util.function.IntBiObjConsumer;
import com.landawn.abacus.util.function.IntBiObjFunction;
import com.landawn.abacus.util.function.IntBiObjPredicate;
import com.landawn.abacus.util.function.IntBiPredicate;
import com.landawn.abacus.util.function.IntBinaryOperator;
import com.landawn.abacus.util.function.IntConsumer;
import com.landawn.abacus.util.function.IntFunction;
import com.landawn.abacus.util.function.IntObjConsumer;
import com.landawn.abacus.util.function.IntObjFunction;
import com.landawn.abacus.util.function.IntObjPredicate;
import com.landawn.abacus.util.function.IntPredicate;
import com.landawn.abacus.util.function.LongBiFunction;
import com.landawn.abacus.util.function.LongBiPredicate;
import com.landawn.abacus.util.function.LongBinaryOperator;
import com.landawn.abacus.util.function.LongConsumer;
import com.landawn.abacus.util.function.LongFunction;
import com.landawn.abacus.util.function.LongPredicate;
import com.landawn.abacus.util.function.LongSupplier;
import com.landawn.abacus.util.function.Predicate;
import com.landawn.abacus.util.function.QuadFunction;
import com.landawn.abacus.util.function.Runnable;
import com.landawn.abacus.util.function.ShortBiFunction;
import com.landawn.abacus.util.function.ShortBiPredicate;
import com.landawn.abacus.util.function.ShortBinaryOperator;
import com.landawn.abacus.util.function.ShortConsumer;
import com.landawn.abacus.util.function.ShortFunction;
import com.landawn.abacus.util.function.ShortPredicate;
import com.landawn.abacus.util.function.Supplier;
import com.landawn.abacus.util.function.ToBooleanFunction;
import com.landawn.abacus.util.function.ToByteFunction;
import com.landawn.abacus.util.function.ToCharFunction;
import com.landawn.abacus.util.function.ToDoubleFunction;
import com.landawn.abacus.util.function.ToFloatFunction;
import com.landawn.abacus.util.function.ToIntFunction;
import com.landawn.abacus.util.function.ToLongFunction;
import com.landawn.abacus.util.function.ToShortFunction;
import com.landawn.abacus.util.function.TriConsumer;
import com.landawn.abacus.util.function.TriFunction;
import com.landawn.abacus.util.function.TriPredicate;
import com.landawn.abacus.util.function.UnaryOperator;
/**
* Factory utility class for functional interfaces.
*
*
* Note: Usually you shouldn't cache or reuse any Function/Predicate/Consumer/... created by calling the methods in this class.
* These methods should be called every time.
*
*
*
*
*
* {@code Map map = N.asMap("a", 1, "b", 2, "c", 3);}
* // Instead of
* {@code Stream.of(map).filter(e -> e.getKey().equals("a") || e.getKey().equals("b")).toMap(e -> e.getKey(), e -> e.getValue());}
* // Using Fn
* {@code Stream.of(map).filter(Fn.testByKey(k -> k.equals("a") || k.equals("b"))).collect(Collectors.toMap());}
*
*
*
*
*
*
*
*/
@SuppressWarnings({ "java:S6539", "java:S1192", "java:S1221", "java:S1452", "java:S2445" })
public final class Fn {
private static final Object NONE = ClassUtil.createNullMask();
private static final Timer timer = new Timer();
// @SuppressWarnings("rawtypes")
// public static final IntFunction> FACTORY_OF_MAP = (IntFunction) Factory.MAP_FACTORY;
//
// @SuppressWarnings("rawtypes")
// public static final IntFunction> FACTORY_OF_LINKED_HASH_MAP = (IntFunction) Factory.LINKED_HASH_MAP_FACTORY;
//
// @SuppressWarnings("rawtypes")
// public static final Supplier> SUPPLIER_OF_MAP = (Supplier) Suppliers.MAP;
//
// @SuppressWarnings("rawtypes")
// public static final Supplier> SUPPLIER_OF_LINKED_HASH_MAP = (Supplier) Suppliers.LINKED_HASH_MAP;
private static final Runnable EMPTY_ACTION = () -> {
};
@SuppressWarnings("rawtypes")
private static final Consumer DO_NOTHING = value -> {
// do nothing.
};
private static final Consumer CLOSE = IOUtil::close;
private static final Consumer CLOSE_QUIETLY = IOUtil::closeQuietly;
@SuppressWarnings("rawtypes")
private static final BiConsumer PRINTLN_EQUAL = (key, value) -> N.println(Strings.concat(N.toString(key), "=", N.toString(value)));
@SuppressWarnings("rawtypes")
private static final BiConsumer PRINTLN_HYPHEN = (key, value) -> N.println(Strings.concat(N.toString(key), "-", N.toString(value)));
@SuppressWarnings("rawtypes")
private static final BiConsumer PRINTLN_UNDERSCORE = (key, value) -> N.println(Strings.concat(N.toString(key), "_", N.toString(value)));
@SuppressWarnings("rawtypes")
private static final BiConsumer PRINTLN_COLON = (key, value) -> N.println(Strings.concat(N.toString(key), ":", N.toString(value)));
@SuppressWarnings("rawtypes")
private static final BiConsumer PRINTLN_COLON_SPACE = (key, value) -> N.println(Strings.concat(N.toString(key), ": ", N.toString(value)));
@SuppressWarnings("rawtypes")
private static final BiConsumer PRINTLN_COMMA = (key, value) -> N.println(Strings.concat(N.toString(key), ",", N.toString(value)));
@SuppressWarnings("rawtypes")
private static final BiConsumer PRINTLN_COMMA_SPACE = (key, value) -> N.println(Strings.concat(N.toString(key), ", ", N.toString(value)));
@SuppressWarnings("rawtypes")
private static final BiConsumer PRINTLN_EMPTY = (key, value) -> N.println(Strings.concat(N.toString(key), N.toString(value)));
@SuppressWarnings("rawtypes")
private static final Consumer PRINTLN = N::println;
@SuppressWarnings("rawtypes")
private static final Function TO_STRING = N::toString;
private static final UnaryOperator TO_CAMEL_CASE = Strings::toCamelCase;
private static final UnaryOperator TO_LOWER_CASE = Strings::toLowerCase;
private static final UnaryOperator TO_LOWER_CASE_WITH_UNDERSCORE = Strings::toLowerCaseWithUnderscore;
private static final UnaryOperator TO_UPPER_CASE = Strings::toUpperCase;
private static final UnaryOperator TO_UPPER_CASE_WITH_UNDERSCORE = Strings::toUpperCaseWithUnderscore;
private static final Function TO_RUNTIME_EXCEPTION = e -> ExceptionUtil.toRuntimeException(e, true);
@SuppressWarnings("rawtypes")
private static final BiFunction COMPARE = N::compare;
@SuppressWarnings("rawtypes")
private static final Function IDENTITY = t -> t;
private static final UnaryOperator TRIM = Strings::trim;
private static final UnaryOperator TRIM_TO_EMPTY = Strings::trimToEmpty;
private static final UnaryOperator TRIM_TO_NULL = Strings::trimToNull;
private static final UnaryOperator STRIP = Strings::strip;
private static final UnaryOperator STRIP_TO_EMPTY = Strings::stripToEmpty;
private static final UnaryOperator STRIP_TO_NULL = Strings::stripToNull;
private static final UnaryOperator NULL_TO_EMPTY = t -> t == null ? Strings.EMPTY_STRING : t;
@SuppressWarnings("rawtypes")
private static final UnaryOperator NULL_TO_EMPTY_LIST = t -> t == null ? N.emptyList() : t;
@SuppressWarnings("rawtypes")
private static final UnaryOperator NULL_TO_EMPTY_SET = t -> t == null ? N.emptySet() : t;
@SuppressWarnings("rawtypes")
private static final UnaryOperator NULL_TO_EMPTY_MAP = t -> t == null ? N.emptyMap() : t;
private static final Function LENGTH = t -> t == null ? 0 : t.length();
private static final Function LEN = t -> t == null ? 0 : t.length;
@SuppressWarnings("rawtypes")
private static final Function SIZE = t -> t == null ? 0 : t.size();
@SuppressWarnings("rawtypes")
private static final Function SIZE_MAP = t -> t == null ? 0 : t.size();
private static final Function, Object> KEY = Entry::getKey;
private static final Function, Object> VALUE = Entry::getValue;
private static final Function, Object> LEFT = Pair::getLeft;
private static final Function, Object> RIGHT = Pair::getRight;
private static final Function, Map.Entry> INVERSE = t -> new ImmutableEntry<>(t.getValue(), t.getKey());
private static final BiFunction> ENTRY = ImmutableEntry::new;
private static final BiFunction> PAIR = Pair::of;
private static final TriFunction> TRIPLE = Triple::of;
private static final Function> TUPLE_1 = Tuple::of;
private static final BiFunction> TUPLE_2 = Tuple::of;
private static final TriFunction> TUPLE_3 = Tuple::of;
private static final QuadFunction> TUPLE_4 = Tuple::of;
@SuppressWarnings("rawtypes")
private static final Predicate ALWAYS_TRUE = value -> true;
@SuppressWarnings("rawtypes")
private static final Predicate ALWAYS_FALSE = value -> false;
@SuppressWarnings("rawtypes")
private static final Predicate IS_NULL = Objects::isNull;
private static final Predicate IS_EMPTY = Strings::isEmpty;
private static final Predicate IS_BLANK = Strings::isBlank;
@SuppressWarnings("rawtypes")
private static final Predicate NOT_NULL = Objects::nonNull;
private static final Predicate IS_NOT_EMPTY = Strings::isNotEmpty;
private static final Predicate IS_NOT_BLANK = Strings::isNotBlank;
private static final Predicate IS_FILE = file -> file != null && file.isFile();
private static final Predicate IS_DIRECTORY = file -> file != null && file.isDirectory();
public static final ToBooleanFunction GET_AS_BOOLEAN = OptionalBoolean::get;
public static final ToCharFunction GET_AS_CHAR = OptionalChar::get;
public static final ToByteFunction GET_AS_BYTE = OptionalByte::get;
public static final ToShortFunction GET_AS_SHORT = OptionalShort::get;
public static final ToIntFunction GET_AS_INT = OptionalInt::get;
public static final ToLongFunction GET_AS_LONG = OptionalLong::get;
public static final ToFloatFunction GET_AS_FLOAT = OptionalFloat::get;
public static final ToDoubleFunction GET_AS_DOUBLE = OptionalDouble::get;
public static final ToIntFunction GET_AS_INT_JDK = java.util.OptionalInt::getAsInt;
public static final ToLongFunction GET_AS_LONG_JDK = java.util.OptionalLong::getAsLong;
public static final ToDoubleFunction GET_AS_DOUBLE_JDK = java.util.OptionalDouble::getAsDouble;
public static final Predicate IS_PRESENT_BOOLEAN = OptionalBoolean::isPresent;
public static final Predicate IS_PRESENT_CHAR = OptionalChar::isPresent;
public static final Predicate IS_PRESENT_BYTE = OptionalByte::isPresent;
public static final Predicate IS_PRESENT_SHORT = OptionalShort::isPresent;
public static final Predicate IS_PRESENT_INT = OptionalInt::isPresent;
public static final Predicate IS_PRESENT_LONG = OptionalLong::isPresent;
public static final Predicate IS_PRESENT_FLOAT = OptionalFloat::isPresent;
public static final Predicate IS_PRESENT_DOUBLE = OptionalDouble::isPresent;
public static final Predicate IS_PRESENT_INT_JDK = java.util.OptionalInt::isPresent;
public static final Predicate IS_PRESENT_LONG_JDK = java.util.OptionalLong::isPresent;
public static final Predicate IS_PRESENT_DOUBLE_JDK = java.util.OptionalDouble::isPresent;
Fn() {
// for extension.
}
// /**
// *
// * @param
// * @param supplier
// * @return
// */
// public static T get(final java.util.function.Supplier supplier) {
// return supplier.get();
// }
/**
* Returns a {@code Supplier} which returns a single instance created by calling the specified {@code supplier.get()}.
*
* @param
* @param supplier
* @return
*/
public static Supplier memoize(final java.util.function.Supplier supplier) {
return LazyInitializer.of(supplier);
}
// Copied from Google Guava under Apache License v2.
/**
* Copied from Google Guava under Apache License v2.
*
*
*
* Returns a supplier that caches the instance supplied by the delegate and removes the cached
* value after the specified time has passed. Subsequent calls to {@code get()} return the cached
* value if the expiration time has not passed. After the expiration time, a new value is
* retrieved, cached, and returned. See: memoization
*
* The returned supplier is thread-safe. The supplier's serialized form does not contain the
* cached value, which will be recalculated when {@code get()} is called on the reserialized
* instance. The actual memoization does not happen when the underlying delegate throws an
* exception.
*
*
When the underlying delegate throws an exception then this memorizing supplier will keep
* delegating calls until it returns valid data.
*
* @param
* @param supplier
* @param duration the length of time after a value is created that it should stop being returned
* by subsequent {@code get()} calls
* @param unit the unit that {@code duration} is expressed in
* @return
* @throws IllegalArgumentException if {@code duration} is not positive
*/
public static Supplier memoizeWithExpiration(final java.util.function.Supplier supplier, final long duration, final TimeUnit unit)
throws IllegalArgumentException {
N.checkArgNotNull(supplier, cs.Supplier);
N.checkArgument(duration > 0, "duration (%s %s) must be > 0", duration, unit);
return new Supplier<>() {
private final java.util.function.Supplier delegate = supplier;
private final long durationNanos = unit.toNanos(duration);
private volatile T value;
// The special value 0 means "not yet initialized".
private volatile long expirationNanos = 0;
@Override
public T get() {
// Another variant of Double-Checked Locking.
//
// We use two volatile reads. We could reduce this to one by
// putting our fields into a holder class, but (at least on x86)
// the extra memory consumption and indirection are more
// expensive than the extra volatile reads.
long nanos = expirationNanos;
final long now = System.nanoTime();
if (nanos == 0 || now - nanos >= 0) {
synchronized (this) {
if (nanos == expirationNanos) { // recheck for lost race
final T t = delegate.get();
value = t;
nanos = now + durationNanos;
// In the very unlikely event that nanos is 0, set it to 1;
// no one will notice 1 ns of tardiness.
expirationNanos = (nanos == 0) ? 1 : nanos;
return t;
}
}
}
// This is safe because we checked `expirationNanos`.
return value;
}
};
}
// /**
// *
// * @param
// * @param
// * @param func
// * @return
// */
// @Beta
// @SequentialOnly
// @Stateful
// public static IntFunction memoize(final IntFunction extends R> func) {
// return new IntFunction() {
// private volatile R resultForNull = (R) NONE;
//
// @Override
// public R apply(int t) {
// R result = resultForNull;
//
// if (result == NONE) {
// synchronized (this) {
// if (resultForNull == NONE) {
// resultForNull = func.apply(t);
// }
//
// result = resultForNull;
// }
// }
//
// return result;
// }
// };
// }
/**
*
* @param
* @param
* @param func
* @return
*/
public static Function memoize(final java.util.function.Function super T, ? extends R> func) {
return new Function<>() {
private final R none = (R) NONE;
private final Map resultMap = new ConcurrentHashMap<>();
private volatile R resultForNull = none; //NOSONAR
@SuppressFBWarnings("NP_LOAD_OF_KNOWN_NULL_VALUE")
@Override
public R apply(final T t) {
R result = null;
if (t == null) {
result = resultForNull;
if (result == none) {
synchronized (this) {
if (resultForNull == none) {
resultForNull = func.apply(null);
}
result = resultForNull;
}
}
} else {
result = resultMap.get(t);
if (result == null) {
result = func.apply(t);
resultMap.put(t, result == null ? none : result);
}
}
return result == none ? null : result;
}
};
}
// /**
// * Only for temporary use in sequential stream/single thread, not for parallel stream/multiple threads.
// * The returned Collection will clean up before it's returned every time when {@code get} is called.
// * Don't save the returned Collection object or use it to save objects.
// *
// * @param
// * @param
// * @param supplier
// * @return
// * @see {@code Stream.split/sliding};
// * @deprecated
// */
// @Deprecated
// @Beta
// @SequentialOnly
// @Stateful
// public static > Supplier extends C> reuse(final java.util.function.Supplier extends C> supplier) {
// return new Supplier<>() {
// private C c;
//
// @Override
// public C get() {
// if (c == null) {
// c = supplier.get();
// } else if (c.size() > 0) {
// c.clear();
// }
//
// return c;
// }
// };
// }
//
// /**
// * Only for temporary use in sequential stream/single thread, not for parallel stream/multiple threads.
// * The returned Collection will clean up before it's returned every time when {@code get} is called.
// * Don't save the returned Collection object or use it to save objects.
// *
// * @param
// * @param
// * @param supplier
// * @return
// * @see {@code Stream.split/sliding};
// * @deprecated
// */
// @Deprecated
// @Beta
// @SequentialOnly
// @Stateful
// public static > IntFunction extends C> reuse(final java.util.function.IntFunction extends C> supplier) {
// return new IntFunction<>() {
// private C c;
//
// @Override
// public C apply(int size) {
// if (c == null) {
// c = supplier.apply(size);
// } else if (c.size() > 0) {
// c.clear();
// }
//
// return c;
// }
// };
// }
/**
*
* @param closeable
* @return
*/
public static Runnable close(final AutoCloseable closeable) {
return new Runnable() {
private volatile boolean isClosed = false;
@Override
public void run() {
if (isClosed) {
return;
}
isClosed = true;
IOUtil.close(closeable);
}
};
}
/**
*
* @param a
* @return
*/
@SafeVarargs
public static Runnable closeAll(final AutoCloseable... a) {
return new Runnable() {
private volatile boolean isClosed = false;
@Override
public void run() {
if (isClosed) {
return;
}
isClosed = true;
IOUtil.closeAll(a);
}
};
}
/**
*
* @param c
* @return
*/
public static Runnable closeAll(final Collection extends AutoCloseable> c) {
return new Runnable() {
private volatile boolean isClosed = false;
@Override
public void run() {
if (isClosed) {
return;
}
isClosed = true;
IOUtil.closeAll(c);
}
};
}
/**
*
* @param closeable
* @return
*/
public static Runnable closeQuietly(final AutoCloseable closeable) {
return new Runnable() {
private volatile boolean isClosed = false;
@Override
public void run() {
if (isClosed) {
return;
}
isClosed = true;
IOUtil.closeQuietly(closeable);
}
};
}
/**
* Close all quietly.
*
* @param a
* @return
*/
@SafeVarargs
public static Runnable closeAllQuietly(final AutoCloseable... a) {
return new Runnable() {
private volatile boolean isClosed = false;
@Override
public void run() {
if (isClosed) {
return;
}
isClosed = true;
IOUtil.closeAllQuietly(a);
}
};
}
/**
* Close all quietly.
*
* @param c
* @return
*/
public static Runnable closeAllQuietly(final Collection extends AutoCloseable> c) {
return new Runnable() {
private volatile boolean isClosed = false;
@Override
public void run() {
if (isClosed) {
return;
}
isClosed = true;
IOUtil.closeAllQuietly(c);
}
};
}
public static Runnable emptyAction() {
return EMPTY_ACTION;
}
/**
*
* @param service
* @return
*/
public static Runnable shutDown(final ExecutorService service) {
return new Runnable() {
private volatile boolean isClosed = false;
@Override
public void run() {
if (isClosed) {
return;
}
isClosed = true;
service.shutdown();
}
};
}
/**
*
* @param service
* @param terminationTimeout
* @param timeUnit
* @return
*/
public static Runnable shutDown(final ExecutorService service, final long terminationTimeout, final TimeUnit timeUnit) {
return new Runnable() {
private volatile boolean isClosed = false;
@Override
public void run() {
if (isClosed) {
return;
}
isClosed = true;
try {
service.shutdown();
//noinspection ResultOfMethodCallIgnored
service.awaitTermination(terminationTimeout, timeUnit);
} catch (final InterruptedException e) {
// ignore.
}
}
};
}
/**
*
* @param
* @return
*/
public static Consumer doNothing() {
return DO_NOTHING;
}
/**
*
* @param
* @param errorMessage
* @return
*/
public static Consumer throwRuntimeException(final String errorMessage) {
return t -> {
throw new RuntimeException(errorMessage);
};
}
/**
*
* @param
* @param exceptionSupplier
* @return
*/
public static Consumer throwException(final java.util.function.Supplier extends RuntimeException> exceptionSupplier) {
return t -> {
throw exceptionSupplier.get();
};
}
public static Function toRuntimeException() {
return TO_RUNTIME_EXCEPTION;
}
/**
*
* @param
* @return
*/
public static Consumer close() {
return (Consumer) CLOSE;
}
/**
*
* @param
* @return
*/
public static Consumer closeQuietly() {
return (Consumer) CLOSE_QUIETLY;
}
/**
*
* @param
* @param millis
* @return
*/
public static Consumer sleep(final long millis) {
return t -> N.sleep(millis);
}
/**
*
* @param
* @param millis
* @return
*/
public static Consumer sleepUninterruptibly(final long millis) {
return t -> N.sleepUninterruptibly(millis);
}
/**
* Returns a stateful {@code Consumer}. Don't save or cache for reuse
*
* @param
* @param permitsPerSecond
* @return
* @see RateLimiter#acquire()
* @see RateLimiter#create(double)
*/
@Stateful
public static Consumer rateLimiter(final double permitsPerSecond) {
return rateLimiter(RateLimiter.create(permitsPerSecond));
}
/**
* Returns a stateful {@code Consumer}. Don't save or cache for reuse
*
* @param
* @param rateLimiter
* @return
* @see RateLimiter#acquire()
*/
@Stateful
public static Consumer rateLimiter(final RateLimiter rateLimiter) {
return t -> rateLimiter.acquire();
}
/**
*
* @param
* @return
*/
public static Consumer println() {
return PRINTLN;
}
/**
*
* @param
* @param
* @param separator
* @return
* @throws IllegalArgumentException
*/
public static BiConsumer println(final String separator) throws IllegalArgumentException {
N.checkArgNotNull(separator);
switch (separator) { // NOSONAR
case "=":
return PRINTLN_EQUAL;
case ":":
return PRINTLN_COLON;
case ": ":
return PRINTLN_COLON_SPACE;
case "-":
return PRINTLN_HYPHEN;
case "_":
return PRINTLN_UNDERSCORE;
case ",":
return PRINTLN_COMMA;
case ", ":
return PRINTLN_COMMA_SPACE;
case "":
return PRINTLN_EMPTY;
default:
return (t, u) -> N.println(t + separator + u);
}
}
/**
*
* @param
* @return
*/
public static Function toStr() {
return TO_STRING;
}
/**
* To camel case.
*
* @return
*/
public static UnaryOperator toCamelCase() {
return TO_CAMEL_CASE;
}
/**
* To lower case.
*
* @return
*/
public static UnaryOperator toLowerCase() {
return TO_LOWER_CASE;
}
/**
* To lower case with underscore.
*
* @return
*/
public static UnaryOperator toLowerCaseWithUnderscore() {
return TO_LOWER_CASE_WITH_UNDERSCORE;
}
/**
* To upper case.
*
* @return
*/
public static UnaryOperator toUpperCase() {
return TO_UPPER_CASE;
}
/**
* To upper case with underscore.
*
* @return
*/
public static UnaryOperator toUpperCaseWithUnderscore() {
return TO_UPPER_CASE_WITH_UNDERSCORE;
}
@SuppressWarnings("rawtypes")
private static final Function TO_JSON = N::toJson;
/**
*
* @param
* @return
*/
public static Function toJson() {
return TO_JSON;
}
@SuppressWarnings("rawtypes")
private static final Function TO_XML = N::toXml;
/**
*
* @param
* @return
*/
public static Function toXml() {
return TO_XML;
}
/**
*
* @param
* @return
*/
public static Function identity() {
return IDENTITY;
}
/**
*
* @param the key type
* @param
* @param keyExtractor
* @return
* @throws IllegalArgumentException
*/
public static Function> keyed(final java.util.function.Function super T, K> keyExtractor) throws IllegalArgumentException {
N.checkArgNotNull(keyExtractor);
return t -> Keyed.of(keyExtractor.apply(t), t);
}
private static final Function, Object> VAL = Keyed::val;
private static final Function, Object>, Object> KK_VAL = t -> t.getKey().val();
/**
*
* @param the key type
* @param
* @return
*/
@SuppressWarnings("rawtypes")
public static Function, T> val() {
return (Function) VAL;
}
/**
*
* @param
* @param the key type
* @param the value type
* @return
*/
@SuppressWarnings("rawtypes")
public static Function, V>, T> kkv() {
return (Function) KK_VAL;
}
private static final Function> WRAP = Wrapper::of;
/**
*
* @param
* @return
*/
@SuppressWarnings("rawtypes")
public static Function> wrap() {
return (Function) WRAP;
}
/**
*
* @param
* @param hashFunction
* @param equalsFunction
* @return
* @throws IllegalArgumentException
*/
public static Function> wrap(final java.util.function.ToIntFunction super T> hashFunction,
final java.util.function.BiPredicate super T, ? super T> equalsFunction) throws IllegalArgumentException {
N.checkArgNotNull(hashFunction);
N.checkArgNotNull(equalsFunction);
return t -> Wrapper.of(t, hashFunction, equalsFunction);
}
private static final Function, Object> UNWRAP = Wrapper::value;
/**
*
* @param
* @return
*/
@SuppressWarnings("rawtypes")
public static Function, T> unwrap() {
return (Function) UNWRAP;
}
/**
*
* @param the key type
* @param the value type
* @return
*/
@SuppressWarnings("rawtypes")
public static Function, K> key() {
return (Function) KEY;
}
/**
*
* @param the key type
* @param the value type
* @return
*/
@SuppressWarnings("rawtypes")
public static Function, V> value() {
return (Function) VALUE;
}
/**
*
* @param
* @param
* @return
*/
@SuppressWarnings("rawtypes")
public static Function, L> left() {
return (Function) LEFT;
}
/**
*
* @param
* @param
* @return
*/
@SuppressWarnings("rawtypes")
public static Function, R> right() {
return (Function) RIGHT;
}
/**
*
* @param the key type
* @param the value type
* @return
*/
@SuppressWarnings("rawtypes")
public static Function, Entry> inverse() {
return (Function) INVERSE;
}
/**
*
* @param the key type
* @param the value type
* @return
*/
@SuppressWarnings("rawtypes")
public static BiFunction> entry() {
return (BiFunction) ENTRY;
}
/**
*
* @param the key type
* @param the value type
* @param key
* @return
* @deprecated replaced by {@code Fn#entryWithKey(Object)}
*/
@Deprecated
public static Function> entry(final K key) {
return entryWithKey(key);
}
/**
*
* @param the key type
* @param the value type
* @param keyExtractor
* @return
* @deprecated replaced by {@code Fn#entryByKeyMapper(Function)}
*/
@Deprecated
public static Function> entry(final java.util.function.Function super V, K> keyExtractor) {
return entryByKeyMapper(keyExtractor);
}
/**
*
* @param the key type
* @param the value type
* @param key
* @return
*/
public static Function> entryWithKey(final K key) {
return v -> new ImmutableEntry<>(key, v);
}
/**
*
* @param the key type
* @param the value type
* @param keyExtractor
* @return
* @throws IllegalArgumentException
*/
public static Function> entryByKeyMapper(final java.util.function.Function super V, K> keyExtractor)
throws IllegalArgumentException {
N.checkArgNotNull(keyExtractor);
return v -> new ImmutableEntry<>(keyExtractor.apply(v), v);
}
/**
*
* @param the key type
* @param the value type
* @param value
* @return
*/
public static Function> entryWithValue(final V value) {
return k -> new ImmutableEntry<>(k, value);
}
/**
*
* @param the key type
* @param the value type
* @param valueExtractor
* @return
* @throws IllegalArgumentException
*/
public static Function> entryByValueMapper(final java.util.function.Function super K, V> valueExtractor)
throws IllegalArgumentException {
N.checkArgNotNull(valueExtractor);
return k -> new ImmutableEntry<>(k, valueExtractor.apply(k));
}
/**
*
* @param
* @param
* @return
*/
@SuppressWarnings("rawtypes")
public static BiFunction> pair() {
return (BiFunction) PAIR;
}
/**
*
* @param
* @param
* @param
* @return
*/
@SuppressWarnings("rawtypes")
public static TriFunction> triple() {
return (TriFunction) TRIPLE;
}
/**
*
* @param
* @return
*/
@SuppressWarnings("rawtypes")
public static Function> tuple1() {
return (Function) TUPLE_1;
}
/**
*
* @param
* @param
* @return
*/
@SuppressWarnings("rawtypes")
public static BiFunction> tuple2() {
return (BiFunction) TUPLE_2;
}
/**
*
* @param
* @param
* @param
* @return
*/
@SuppressWarnings("rawtypes")
public static TriFunction > tuple3() {
return (TriFunction) TUPLE_3;
}
/**
*
* @param
* @param
* @param
* @param
* @return
*/
@SuppressWarnings({ "rawtypes" })
public static QuadFunction > tuple4() {
return (QuadFunction) TUPLE_4;
}
public static UnaryOperator