cn.keayuan.util.AgentList Maven / Gradle / Ivy
The newest version!
package cn.keayuan.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import cn.keayuan.util.function.Consumer;
import cn.keayuan.util.function.Function;
import cn.keayuan.util.function.ObjIntConsumer;
import cn.keayuan.util.function.ObjIntFunction;
import cn.keayuan.util.function.ObjIntPredicate;
/**
* Created by keayuan on 2024.9.12.
*
* @author keayuan
*/
public class AgentList implements Agent {
public final List value;
@SafeVarargs
@SuppressWarnings("varargs")
public static AgentList as(T... ts) {
return new AgentList<>(Arrays.asList(ts));
}
public static AgentList as(List list) {
return new AgentList<>(list);
}
public static AgentList empty() {
return new AgentList<>(new ArrayList<>());
}
public AgentList(List value) {
this.value = value;
}
public boolean isNull() {
return value == null;
}
public boolean isEmpty() {
return value == null || value.isEmpty();
}
public int size() {
return isNull() ? 0 : value.size();
}
public boolean isNotEmpty() {
return value != null && !value.isEmpty();
}
public E first() {
return isEmpty() ? null : value.get(0);
}
public E getLast() {
return isEmpty() ? null : value.get(value.size() - 1);
}
@Override
public AgentList filter(ObjIntPredicate predicate) {
ObjectUtils.requireNonNull(predicate);
if (value == null) return this;
List ret = new ArrayList<>();
forEach((e, i) -> {if (predicate.test(e, i)) ret.add(e);});
return new AgentList<>(ret);
}
public void forEach(Consumer consumer) {
ObjectUtils.requireNonNull(consumer);
if (isEmpty()) return;
for (E e : value) {
consumer.accept(e);
}
}
@Override
public void forEach(boolean reverse, ObjIntConsumer consumer) {
ObjectUtils.requireNonNull(consumer);
if (isEmpty()) return;
forEachInterruptibly(reverse, (e, i) -> {
consumer.accept(e, i);
return false;
});
}
@Override
public void forEachInterruptibly(boolean reverse, ObjIntPredicate function) {
ObjectUtils.requireNonNull(function);
if (isEmpty()) return;
if (reverse) {
for (int i = size() - 1; i >= 0; i--) {
if (function.test(value.get(i), i)) return;
}
} else {
int size = size();
for (int i = 0; i < size; i++) {
if (function.test(value.get(i), i)) return;
}
}
}
@Override
public AgentList map(Function function) {
ObjectUtils.requireNonNull(function);
if (isEmpty()) return empty();
ArrayList array = new ArrayList<>();
forEach(e -> array.add(function.apply(e)));
return new AgentList<>(array);
}
@Override
public AgentList map(ObjIntFunction function) {
ObjectUtils.requireNonNull(function);
if (isEmpty()) return empty();
ArrayList array = new ArrayList<>();
forEach((e, i) -> array.add(function.apply(e, i)));
return new AgentList<>(array);
}
public List get() {
return value;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy