Improve runtime

This commit is contained in:
Andrea Cavalli 2022-06-22 19:05:26 +02:00
parent 8d72c9cfc5
commit c26aa9027e

View File

@ -1,6 +1,11 @@
package it.cavallium.data.generator; package it.cavallium.data.generator;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -52,4 +57,62 @@ public interface TypedNullable<T> extends NativeNullable<T> {
default boolean isEmpty() { default boolean isEmpty() {
return getNullable() == null; return getNullable() == null;
} }
default <U, TN extends TypedNullable<U>> @NotNull TN map(
@NotNull Function<@NotNull T, @NotNull U> value,
@NotNull Function<@Nullable U, @NotNull TN> nullableConstructor) {
var nullable = getNullable();
if (nullable != null) {
var val = value.apply(nullable);
Objects.requireNonNull(val, "Mapped value must not be null");
return nullableConstructor.apply(val);
} else {
return nullableConstructor.apply(null);
}
}
default <U> @NotNull Optional<U> map(@NotNull Function<@NotNull T, @NotNull U> value) {
var nullable = getNullable();
if (nullable != null) {
var val = value.apply(nullable);
return Optional.of(val);
} else {
return Optional.empty();
}
}
@SuppressWarnings("unchecked")
default <TN extends TypedNullable<T>> @NotNull TN filter(
@NotNull Predicate<@NotNull T> value,
@NotNull Supplier<TN> nullableConstructor) {
var nullable = getNullable();
if (nullable != null) {
var filter = value.test(nullable);
if (!filter) {
return nullableConstructor.get();
}
}
return (TN) this;
}
default @NotNull Optional<T> filter(@NotNull Predicate<@NotNull T> value) {
var nullable = getNullable();
if (nullable != null) {
var filter = value.test(nullable);
if (!filter) {
return Optional.empty();
}
}
return Optional.ofNullable(nullable);
}
default @NotNull Optional<T> toOptional() {
var nullable = getNullable();
return Optional.ofNullable(nullable);
}
default @NotNull Stream<T> stream() {
var nullable = getNullable();
return Stream.ofNullable(nullable);
}
} }