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

one.xingyi.optics.IFold Maven / Gradle / Ivy

package one.xingyi.optics;

import one.xingyi.helpers.StreamHelper;
import one.xingyi.interfaces.ConsumerWithException;
import one.xingyi.tuples.Tuple2;


import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public interface IFold {
    static  IFold of(Function> allFn) {
        return new Fold<>(allFn);
    }

    static  IFold ofWithoutNulls(Function> allFn) {
        return new Fold<>(main -> allFn.apply(main).filter(Objects::nonNull));
    }

    static  IFold, T> collectionFold() {
        return new Fold<>(Collection::stream);
    }
    Stream all(Main main);
    List allAsList(Main main);

     IFold chainFold(IFold t);

    void forEach(Main main, ConsumerWithException consumer) throws Exception;
    IFold lastN(int n);

    IFold filter(Predicate p);

    IFold unique();
     IFold map(Function fn);
     IFold merge(IFold other, IISO, Merged> iso);

}

abstract class AbstractFold implements IFold {
    public  IFold chainFold(IFold f2) {
        return new Fold(main -> this.all(main).flatMap(f2::all));
    }

    @Override
    public List allAsList(Main main) {
        return all(main).collect(Collectors.toList());
    }
    public IFold lastN(int n) {
        return IFold.of(main -> StreamHelper.lastN(all(main), n));
    }

    public IFold filter(Predicate p) {
        return new Fold<>(main -> this.all(main).filter(p));
    }
    @Override
    public  IFold map(Function fn) {
        return new Fold(main -> this.all(main).map(fn));
    }
    public  IFold merge(IFold other, IISO, Merged> iso) {
        return new Fold<>(main -> this.all(main).flatMap(child -> other.all(main).map(child2 -> iso.get(Tuple2.of(child, child2)))));
    }
    @Override
    public void forEach(Main main, ConsumerWithException consumer) throws Exception {
        for (Iterator iterator = all(main).iterator(); iterator.hasNext(); )
            consumer.accept(iterator.next());
    }
    @Override
    public IFold unique() {
        return IFold.of(main -> all(main).distinct());
    }

}

class Fold extends AbstractFold implements IFold {

    protected final Function> allFn;

    Fold(Function> allFn) {
        this.allFn = allFn;
    }


    public Stream all(Main main) {
        return allFn.apply(main);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy