All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.rx.core.Linq Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
package org.rx.core;

import io.netty.util.internal.ThreadLocalRandom;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.IteratorUtils;
import org.rx.annotation.ErrorCode;
import org.rx.bean.$;
import org.rx.bean.Decimal;
import org.rx.exception.ApplicationException;
import org.rx.util.function.*;

import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.ToDoubleFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import static org.rx.bean.$.$;
import static org.rx.core.Constants.NON_RAW_TYPES;
import static org.rx.core.Constants.NON_UNCHECKED;
import static org.rx.core.Extends.*;

/**
 * https://msdn.microsoft.com/en-us/library/bb738550(v=vs.110).aspx
 */
@Slf4j
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public final class Linq implements Iterable, Serializable {
    private static final long serialVersionUID = -7167070585936243198L;
    static final Linq EMPTY = new Linq<>(Collections.emptyList(), false);

    //region staticMembers
    public static boolean tryAsIterableType(Class type) {
        return Iterable.class.isAssignableFrom(type)
                || type.isArray()
                || Iterator.class.isAssignableFrom(type);
    }

    @SuppressWarnings(NON_UNCHECKED)
    @ErrorCode
    public static  Iterable asIterable(@NonNull Object collection, boolean throwOnFail) {
        if (collection instanceof Iterable) {
            return (Iterable) collection;
        }

        Class type = collection.getClass();
        if (type.isArray()) {
            int length = Array.getLength(collection);
            List list = new ArrayList<>(length);
            for (int i = 0; i < length; i++) {
                list.add((T) Array.get(collection, i));
            }
            return list;
        }

        if (collection instanceof Iterator) {
            return IteratorUtils.asIterable((Iterator) collection);
        }

        if (throwOnFail) {
            throw new ApplicationException(values(type.getSimpleName()));
        }
        return null;
    }

    public static  Linq empty() {
        return (Linq) EMPTY;
    }

    public static  Linq fromIterable(Object iterable) {
        return from(asIterable(iterable, true));
    }

    public static  Linq from(T one) {
        if (one == null) {
            return EMPTY;
        }
        return from(Arrays.toList(one));
    }

    @SafeVarargs
    public static  Linq from(T... array) {
        return from(Arrays.toList(array));
    }

    public static  Linq from(Stream stream) {
        if (stream == null) {
            return EMPTY;
        }
        return from(stream::iterator, stream.isParallel());
    }

    public static  Linq from(Iterable iterable) {
        return from(iterable, false);
    }

    public static  Linq from(Iterable iterable, boolean isParallel) {
        return iterable == null ? EMPTY : new Linq<>(iterable, isParallel);
    }
    //endregion

    //region Member
    private final Iterable data;
    private final boolean parallel;

    public Stream stream() {
        return StreamSupport.stream(data.spliterator(), parallel);
    }

    private  List newList() {
        Collection ts = asCollection();
        int count = ts != null ? ts.size() : 0;
        return parallel ? newConcurrentList(count, false) : new ArrayList<>(count);
    }

    private  Set newSet() {
        Collection ts = asCollection();
        int count = ts != null ? ts.size() : 16;
        return parallel ? Collections.synchronizedSet(new LinkedHashSet<>(count)) : new LinkedHashSet<>(count);
    }

    private  Map newMap() {
        Collection ts = asCollection();
        int count = ts != null ? ts.size() : 16;
        return parallel ? Collections.synchronizedMap(new LinkedHashMap<>(count)) : new LinkedHashMap<>(count);
    }

    private Collection asCollection() {
        return data instanceof Collection ? (Collection) data : null;
    }

    private  Stream newStream(Iterable iterable) {
//        return StreamSupport.stream(iterable.spliterator(), parallel);
        return StreamSupport.stream(iterable.spliterator(), false);
    }

    private  Linq me(Iterable set) {
        return from(set, parallel);
    }

    private  Linq me(Stream stream) {
        return me(stream.collect(Collectors.toList()));
    }

    @SneakyThrows
    private Linq me(EachFunc func, String prevMethod) {
        if (parallel) {
            log.warn("Not support parallel {}", prevMethod);
        }

        Spliterator spliterator = data.spliterator();
        Stream r = StreamSupport.stream(new Spliterators.AbstractSpliterator(spliterator.estimateSize(), spliterator.characteristics()) {
            final AtomicBoolean breaker = new AtomicBoolean();
            final AtomicInteger counter = new AtomicInteger();

            @Override
            public boolean tryAdvance(Consumer action) {
                return spliterator.tryAdvance(p -> {
                    int flags = func.each(p, counter.getAndIncrement());
                    if ((flags & EachFunc.ACCEPT) == EachFunc.ACCEPT) {
                        action.accept(p);
                    }
                    if ((flags & EachFunc.BREAK) == EachFunc.BREAK) {
                        breaker.set(true);
                    }
                }) && !breaker.get();
            }
        }, parallel);
        return me(r);
    }

    @FunctionalInterface
    interface EachFunc {
        int NONE = 0;
        int ACCEPT = 1;
        int BREAK = 1 << 1;

        int each(T item, int index);
    }
    //endregion

    @Override
    public Iterator iterator() {
        return data.iterator();
    }

    @Override
    public void forEach(Consumer action) {
        stream().forEach(action);
    }

    public void forEachOrdered(Consumer action) {
        stream().forEachOrdered(action);
    }

    public  Linq select(BiFunc selector) {
        return me(stream().map(selector));
    }

    public  Linq select(BiFuncWithIndex selector) {
        AtomicInteger counter = new AtomicInteger();
        return me(stream().map(p -> selector.apply(p, counter.getAndIncrement())));
    }

    public  Linq selectMany(BiFunc> selector) {
        return me(stream().flatMap(p -> newStream(selector.apply(p))));
    }

    public  Linq selectMany(BiFuncWithIndex> selector) {
        AtomicInteger counter = new AtomicInteger();
        return me(stream().flatMap(p -> newStream(selector.apply(p, counter.getAndIncrement()))));
    }

    public Linq where(PredicateFunc predicate) {
        return me(stream().filter(predicate));
    }

    public Linq where(PredicateFuncWithIndex predicate) {
        AtomicInteger counter = new AtomicInteger();
        return me(stream().filter(p -> predicate.test(p, counter.getAndIncrement())));
    }

    public  Linq join(Iterable inner, BiPredicate keySelector, TripleFunc resultSelector) {
        return me(stream().flatMap(p -> newStream(inner).filter(p2 -> keySelector.test(p, p2)).map(p3 -> resultSelector.apply(p, p3))));
    }

    public  Linq join(BiFunc innerSelector, BiPredicate keySelector, TripleFunc resultSelector) {
        return join(stream().map(innerSelector).collect(Collectors.toList()), keySelector, resultSelector);
    }

    public  Linq joinMany(BiFunc> innerSelector, BiPredicate keySelector, TripleFunc resultSelector) {
        return join(stream().flatMap(p -> newStream(innerSelector.apply(p))).collect(Collectors.toList()), keySelector, resultSelector);
    }

    public  Linq leftJoin(Iterable right, BiPredicate keySelector, TripleFunc resultSelector) {
        return me(stream().flatMap(p -> {
            if (!newStream(right).anyMatch(p2 -> keySelector.test(p, p2))) {
                return Stream.of(resultSelector.apply(p, null));
            }
            return newStream(right).filter(p2 -> keySelector.test(p, p2)).map(p3 -> resultSelector.apply(p, p3));
        }));
    }

    public  Linq leftJoin(BiFunc innerSelector, BiPredicate keySelector, TripleFunc resultSelector) {
        return leftJoin(stream().map(innerSelector).collect(Collectors.toList()), keySelector, resultSelector);
    }

    public  Linq leftJoinMany(BiFunc> innerSelector, BiPredicate keySelector, TripleFunc resultSelector) {
        return leftJoin(stream().flatMap(p -> newStream(innerSelector.apply(p))).collect(Collectors.toList()), keySelector, resultSelector);
    }

    public boolean all(PredicateFunc predicate) {
        return stream().allMatch(predicate);
    }

    public boolean any() {
        return stream().findAny().isPresent();
    }

    public boolean any(PredicateFunc predicate) {
        return stream().anyMatch(predicate);
    }

    public boolean contains(T item) {
        return stream().anyMatch(p -> p.equals(item));
    }

    public Linq concat(Iterable set) {
        return me(Stream.concat(stream(), newStream(set)));
    }

    public Linq distinct() {
        return me(stream().distinct());
    }

    public Linq except(Iterable set) {
        return me(stream().filter(p -> !newStream(set).anyMatch(p2 -> p2.equals(p))));
    }

    public Linq intersection(Iterable set) {
        return me(stream().filter(p -> newStream(set).anyMatch(p2 -> p2.equals(p))));
    }

    public Linq difference(Iterable set) {
        return Linq.from(CollectionUtils.disjunction(this, set));
    }

    public Linq union(Iterable set) {
        return Linq.from(CollectionUtils.union(this, set));
    }

    //ListUtils.partition()
    public Linq> partition(int size) {
        List> n = newList();
        List a = toList();
        int f = 0, t = 0;
        while (f < a.size()) {
            t = Math.min(t + size, a.size());
            n.add(a.subList(f, t));
            f = t;
        }
        return me(n);
    }

    public Linq orderByRand() {
        return me(stream().sorted(getComparator(p -> ThreadLocalRandom.current().nextInt(0, 100), false)));
    }

    public  Linq orderBy(BiFunc keySelector) {
//        return me(stream().sorted(Comparator.nullsLast(Comparator.comparing((Function) keySelector))));
        return me(stream().sorted(getComparator(keySelector, false)));
    }

    @SuppressWarnings(NON_RAW_TYPES)
    public static  Comparator getComparator(BiFunc keySelector, boolean descending) {
        return (p1, p2) -> {
            Comparable a = as(keySelector.apply(p1), Comparable.class);
            Comparable b = as(keySelector.apply(p2), Comparable.class);
            boolean nullFirst = false;
            if (a == null) {
                return b == null ? 0 : (nullFirst ? -1 : 1);
            }
            if (b == null) {
                return nullFirst ? 1 : -1;
            }
            return descending ? b.compareTo(a) : a.compareTo(b);
        };
    }

    public  Linq orderByDescending(BiFunc keySelector) {
        return me(stream().sorted(getComparator(keySelector, true)));
    }

    public Linq orderByMany(BiFunc> keySelector) {
        return me(stream().sorted(getComparatorMany(keySelector, false)));
    }

    @SuppressWarnings(NON_RAW_TYPES)
    public static  Comparator getComparatorMany(BiFunc> keySelector, boolean descending) {
        return (p1, p2) -> {
            List k1s = keySelector.apply(p1), k2s = keySelector.apply(p2);
            for (int i = 0; i < k1s.size(); i++) {
                Comparable a = as(k1s.get(i), Comparable.class);
                Comparable b = as(k2s.get(i), Comparable.class);
                boolean nullFirst = false;
                if (a == null) {
                    return b == null ? 0 : (nullFirst ? -1 : 1);
                }
                if (b == null) {
                    return nullFirst ? 1 : -1;
                }
                int r = descending ? b.compareTo(a) : a.compareTo(b);
                if (r == 0) {
                    continue;
                }
                return r;
            }
            return 0;
        };
    }

    public Linq orderByDescendingMany(BiFunc> keySelector) {
        return me(stream().sorted(getComparatorMany(keySelector, true)));
    }

    @SuppressWarnings(NON_UNCHECKED)
    public Linq reverse() {
        try {
            return me(stream().sorted((Comparator) Comparator.reverseOrder()));
        } catch (Exception e) {
            log.warn("Try reverse fail, {}", e.getMessage());
            List list = toList();
            Collections.reverse(list);
            return me(list);
        }
    }

    public  Linq groupBy(BiFunc keySelector, TripleFunc, TR> resultSelector) {
        Map> map = stream().collect(Collectors.groupingBy(keySelector, this::newMap, Collectors.toList()));
        List result = newList();
        for (Map.Entry> entry : map.entrySet()) {
            result.add(resultSelector.apply(entry.getKey(), from(entry.getValue())));
        }
        return me(result);
    }

    public  Map groupByIntoMap(BiFunc keySelector, TripleFunc, TR> resultSelector) {
        Map> map = stream().collect(Collectors.groupingBy(keySelector, this::newMap, Collectors.toList()));
        Map result = newMap();
        for (Map.Entry> entry : map.entrySet()) {
            result.put(entry.getKey(), resultSelector.apply(entry.getKey(), Linq.from(entry.getValue())));
        }
        return result;
    }

    public  Linq groupByMany(BiFunc> keySelector, TripleFunc, Linq, TR> resultSelector) {
        Map, List> map = stream().collect(Collectors.groupingBy(keySelector, this::newMap, Collectors.toList()));
        List result = newList();
        for (Map.Entry, List> entry : map.entrySet()) {
            result.add(resultSelector.apply(entry.getKey(), from(entry.getValue())));
        }
        return me(result);
    }

    public Double average(ToDoubleFunction selector) {
        OptionalDouble q = stream().mapToDouble(selector).average();
        return q.isPresent() ? q.getAsDouble() : null;
    }

    public int count() {
        Collection ts = asCollection();
        return ts != null ? ts.size() : (int) stream().count();
    }

    public int count(PredicateFunc predicate) {
        return (int) stream().filter(predicate).count();
    }

    public T max() {
        return max(stream());
    }

    @SuppressWarnings(NON_UNCHECKED)
    private  TR max(Stream stream) {
        return stream.max((Comparator) Comparator.naturalOrder()).orElse(null);
    }

    public  TR max(BiFunc selector) {
        return max(stream().map(selector));
    }

    public T min() {
        return min(stream());
    }

    @SuppressWarnings(NON_UNCHECKED)
    private  TR min(Stream stream) {
        return stream.min((Comparator) Comparator.naturalOrder()).orElse(null);
    }

    public  TR min(BiFunc selector) {
        return min(stream().map(selector));
    }

    public double sum(ToDoubleFunction selector) {
        return stream().mapToDouble(selector).sum();
    }

    public Decimal sumDecimal(BiFunc selector) {
        $ sumValue = $(Decimal.ZERO);
        stream().forEach(p -> sumValue.v = sumValue.v.add(selector.apply(p)));
        return sumValue.v;
    }

    @SuppressWarnings(NON_UNCHECKED)
    public  Linq cast() {
        return (Linq) this;
    }

    @SuppressWarnings(NON_UNCHECKED)
    public  Linq ofType(Class type) {
        return where(p -> p != null && Reflects.isInstance(p, type)).select(p -> (TR) p);
    }

    public T first() {
        return stream().findFirst().get();
    }

    public T first(PredicateFunc predicate) {
        return stream().filter(predicate).findFirst().get();
    }

    public T firstOrDefault() {
        return firstOrDefault((T) null);
    }

    public T firstOrDefault(T defaultValue) {
        return stream().findFirst().orElse(defaultValue);
    }

    public T firstOrDefault(Func defaultValue) {
        return stream().findFirst().orElseGet(defaultValue);
    }

    public T firstOrDefault(PredicateFunc predicate) {
        return stream().filter(predicate).findFirst().orElse(null);
    }

    public T last() {
        T value = lastOrDefault();
        if (value == null) {
            throw new NoSuchElementException("No value present");
        }
        return value;
    }

    public T last(PredicateFunc predicate) {
        return where(predicate).last();
    }

    public T lastOrDefault() {
        T value = null;
        if (data instanceof List) {
            List list = (List) data;
            value = !list.isEmpty() ? list.get(list.size() - 1) : null;
        } else {
            for (T datum : data) {
                value = datum;
            }
        }
        return value;
    }

    public T lastOrDefault(T defaultValue) {
        return ifNull(lastOrDefault(), defaultValue);
    }

    public T lastOrDefault(PredicateFunc predicate) {
        return where(predicate).lastOrDefault();
    }

    public T single() {
        return single(null);
    }

    @ErrorCode
    public T single(PredicateFunc predicate) {
        Stream stream = stream();
        if (predicate != null) {
            stream = stream.filter(predicate);
        }
        List list = stream.limit(2).collect(Collectors.toList());
        if (list.size() != 1) {
            throw new ApplicationException(values(list.size()));
        }
        return list.get(0);
    }

    public T singleOrDefault() {
        return singleOrDefault(null);
    }

    @ErrorCode
    public T singleOrDefault(PredicateFunc predicate) {
        Stream stream = stream();
        if (predicate != null) {
            stream = stream.filter(predicate);
        }
        List list = stream.limit(2).collect(Collectors.toList());
        if (list.size() > 1) {
            throw new ApplicationException(values(list.size()));
        }
        return list.isEmpty() ? null : list.get(0);
    }

    public Linq skip(int count) {
        return me(stream().skip(count));
    }

    public Linq skipWhile(PredicateFunc predicate) {
        return skipWhile((p, i) -> predicate.invoke(p));
    }

    public Linq skipWhile(PredicateFuncWithIndex predicate) {
        AtomicBoolean doAccept = new AtomicBoolean();
        return me((p, i) -> {
            int flags = EachFunc.NONE;
            if (doAccept.get()) {
                flags |= EachFunc.ACCEPT;
                return flags;
            }
            if (!predicate.test(p, i)) {
                doAccept.set(true);
                flags |= EachFunc.ACCEPT;
            }
            return flags;
        }, "skipWhile");
    }

    public Linq take(int count) {
        return me(stream().limit(count));
    }

    public Linq takeWhile(PredicateFunc predicate) {
        return takeWhile((p, i) -> predicate.invoke(p));
    }

    public Linq takeWhile(PredicateFuncWithIndex predicate) {
        return me((p, i) -> {
            int flags = EachFunc.NONE;
            if (!predicate.test(p, i)) {
                flags |= EachFunc.BREAK;
                return flags;
            }
            flags |= EachFunc.ACCEPT;
            return flags;
        }, "takeWhile");
    }

    public String toJoinString(String delimiter) {
        return String.join(delimiter, this.cast());
    }

    public String toJoinString(String delimiter, BiFunc selector) {
        return String.join(delimiter, select(selector));
    }

    @SuppressWarnings(NON_UNCHECKED)
    public T[] toArray() {
        List result = toList();
        Class type = null;
        for (T t : result) {
            if (t == null) {
                continue;
            }
            if (type == null) {
                type = t.getClass();
                continue;
            }
            if (type != t.getClass()) {
                type = null;
                break;
            }
        }
        if (type == null) {
            type = Object.class;
        }
        T[] array = (T[]) Array.newInstance(type, result.size());
        result.toArray(array);
        return array;
    }

    @SuppressWarnings(NON_UNCHECKED)
    public T[] toArray(Class type) {
        List result = toList();
        T[] array = (T[]) Array.newInstance(type, result.size());
        result.toArray(array);
        return array;
    }

    public List toList() {
        if (!parallel && data instanceof List) {
            return (List) data;
        }
        List result = newList();
        for (T item : data) {
            result.add(item);
        }
        return result;
    }

    public Set toSet() {
        if (!parallel && data instanceof Set) {
            return (Set) data;
        }
        Set result = newSet();
        for (T item : data) {
            result.add(item);
        }
        return result;
    }

    public  Map toMap() {
        Map result = newMap();
        for (Map.Entry entry : this.>cast()) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    public  Map toMap(BiFunc keySelector) {
        return toMap(keySelector, p -> p);
    }

    //Collectors.toMap() will throw exception if value is null
    @SneakyThrows
    public  Map toMap(BiFunc keySelector, BiFunc resultSelector) {
        Map result = newMap();
        stream().forEach(item -> result.put(keySelector.apply(item), resultSelector.apply(item)));
        return result;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Linq linq = (Linq) o;
        return parallel == linq.parallel && Objects.equals(data, linq.data);
    }

    @Override
    public int hashCode() {
        return Objects.hash(data, parallel);
    }
}