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

com.jnape.palatable.lambda.lens.lenses.CollectionLens Maven / Gradle / Ivy

There is a newer version: 5.5.0
Show newest version
package com.jnape.palatable.lambda.lens.lenses;

import com.jnape.palatable.lambda.lens.Lens;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;

import static com.jnape.palatable.lambda.lens.Lens.simpleLens;

/**
 * Lenses that operate on {@link Collection}s.
 */
public final class CollectionLens {

    private CollectionLens() {
    }

    /**
     * Convenience static factory method for creating a lens that focuses on a copy of a Collection, given
     * a function that creates the copy. Useful for composition to avoid mutating a Collection reference.
     *
     * @param copyFn the copying function
     * @param     the collection element type
     * @param    the type of the collection
     * @return a lens that focuses on a copy of CX
     */
    public static > Lens.Simple asCopy(Function copyFn) {
        return simpleLens(copyFn, (__, copy) -> copy);
    }

    /**
     * Convenience static factory method for creating a lens that focuses on an arbitrary {@link Collection} as a
     * {@link Set}.
     *
     * @param   the collection element type
     * @param  the type of the collection
     * @return a lens that focuses on a Collection as a Set
     */
    public static > Lens.Simple> asSet() {
        return simpleLens(HashSet::new, (xsL, xsS) -> {
            xsL.retainAll(xsS);
            return xsL;
        });
    }

    /**
     * Convenience static factory method for creating a lens that focuses on a Collection as a Stream.
     *
     * @param   the collection element type
     * @param  the type of the collection
     * @return a lens that focuses on a Collection as a stream.
     */
    public static > Lens.Simple> asStream() {
        return simpleLens(Collection::stream, (xsL, xsS) -> {
            xsL.clear();
            xsS.forEach(xsL::add);
            return xsL;
        });
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy