dev.marksman.collectionviews.Sets Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of collection-views Show documentation
Show all versions of collection-views Show documentation
Low overhead, protected views over Java collections
package dev.marksman.collectionviews;
import com.jnape.palatable.lambda.adt.Maybe;
import com.jnape.palatable.lambda.functions.Fn0;
import java.util.Arrays;
import java.util.Objects;
import static com.jnape.palatable.lambda.adt.Maybe.just;
import static com.jnape.palatable.lambda.adt.Maybe.nothing;
class Sets {
static ImmutableSet empty() {
return EmptySet.emptySet();
}
static Maybe> maybeNonEmptyWrap(java.util.Set underlying) {
Objects.requireNonNull(underlying);
if (underlying.isEmpty()) {
return nothing();
} else {
return just(new WrappedSet<>(underlying));
}
}
static Maybe> maybeNonEmptyWrap(Set underlying) {
if (underlying instanceof NonEmptySet>) {
return just((NonEmptySet) underlying);
} else if (!underlying.isEmpty()) {
return just(new NonEmptySetAdapter<>(underlying));
} else {
return nothing();
}
}
static Fn0 nonEmptyError() {
return () -> new IllegalArgumentException("Cannot construct NonEmptySet from empty input");
}
@SuppressWarnings("varargs")
@SafeVarargs
static ImmutableNonEmptySet nonEmptySetOf(A first, A... more) {
java.util.Set underlying = new java.util.HashSet<>();
underlying.add(first);
underlying.addAll(Arrays.asList(more));
return new ImmutableWrappedSet<>(underlying);
}
static NonEmptySet nonEmptyWrapOrThrow(java.util.Set underlying) {
return getNonEmptyOrThrow(maybeNonEmptyWrap(underlying));
}
static NonEmptySet nonEmptyWrapOrThrow(Set underlying) {
return getNonEmptyOrThrow(maybeNonEmptyWrap(underlying));
}
static Set wrap(java.util.Set underlying) {
Objects.requireNonNull(underlying);
if (underlying.isEmpty()) {
return empty();
} else {
return new WrappedSet<>(underlying);
}
}
private static NonEmptySet getNonEmptyOrThrow(Maybe> maybeResult) {
return maybeResult.orElseThrow(nonEmptyError());
}
}