java-commons/src/main/java/io/gitlab/jfronny/commons/tuple/Single.java

53 lines
1.3 KiB
Java

package io.gitlab.jfronny.commons.tuple;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public record Single<T1>(@Nullable T1 val) {
@Contract(pure = true) @NotNull
public static <T1> Single<T1> of(@Nullable T1 val) {
return new Single<>(val);
}
@Contract(pure = true)
public boolean isNull() {
return val == null;
}
@Contract(pure = true)
public boolean isPresent() {
return val != null;
}
@Contract(pure = true) @NotNull
public Predicate<T1> asEqualsPredicate() {
return val == null ? Objects::isNull : val::equals;
}
@Contract(pure = true) @NotNull
public Predicate<T1> asInstanceEqualsPredicate() {
return v -> v == val;
}
@Contract(pure = true) @NotNull
public Supplier<T1> asSupplier() {
return () -> val;
}
@Contract(pure = true) @NotNull
public <T> Single<T> map(@NotNull Function<T1, T> mapper) {
return new Single<>(Objects.requireNonNull(mapper).apply(val));
}
@Contract(pure = true) @Nullable
public T1 get() {
return val;
}
}