io.polyglotted.common.util.ListBuilder Maven / Gradle / Ivy
package io.polyglotted.common.util;
import com.google.common.collect.ImmutableList;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Supplier;
import static io.polyglotted.common.util.Assertions.checkGte;
import static io.polyglotted.common.util.ReflectionUtil.fieldValue;
import static java.util.Arrays.asList;
@SuppressWarnings({"unused", "WeakerAccess"})
public interface ListBuilder> {
ListBuilder add(E elem);
ListBuilder addAll(Collection elems);
int size();
L build();
default L atleastOne() { checkGte(size(), 1, "size"); return build(); }
static ImmutableListBuilder immutableListBuilder() { return new ImmutableListBuilder<>(); }
static ImmutableList immutableList() { return ImmutableList.of(); }
@SafeVarargs static ImmutableList immutableList(E... elems) { return ListBuilder.immutableListBuilder().addAll(asList(elems)).build(); }
static SimpleListBuilder simpleListBuilder() { return simpleListBuilder(LinkedList::new); }
static SimpleListBuilder simpleListBuilder(Supplier> supplier) { return new SimpleListBuilder<>(supplier.get()); }
static List simpleList() { return new LinkedList<>(); }
@SafeVarargs static List simpleList(E... elems) { return ListBuilder.simpleListBuilder().addAll(asList(elems)).build(); }
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
class ImmutableListBuilder implements ListBuilder> {
private final ImmutableList.Builder builder = ImmutableList.builder();
@Override public ListBuilder> add(E elem) { if (elem != null) builder.add(elem); return this; }
@Override public ListBuilder> addAll(Collection elems) { for (E elem : elems) { add(elem); } return this; }
@Override public int size() { return fieldValue(builder, "size"); }
@Override public ImmutableList build() { return builder.build(); }
}
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
class SimpleListBuilder implements ListBuilder> {
private final List builder;
@Override public ListBuilder> add(E elem) { if (elem != null) builder.add(elem); return this; }
@Override public ListBuilder> addAll(Collection elems) { for (E elem : elems) { add(elem); } return this; }
@Override public int size() { return builder.size(); }
@Override public List build() { return builder; }
}
}