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

com.jnape.palatable.lambda.functions.builtin.fn2.Find Maven / Gradle / Ivy

There is a newer version: 5.5.0
Show newest version
package com.jnape.palatable.lambda.functions.builtin.fn2;

import com.jnape.palatable.lambda.functions.Fn1;
import com.jnape.palatable.lambda.functions.Fn2;
import com.jnape.palatable.lambda.functions.specialized.Predicate;

import java.util.Optional;
import java.util.function.Function;

import static com.jnape.palatable.lambda.functions.builtin.fn1.Head.head;
import static com.jnape.palatable.lambda.functions.builtin.fn2.DropWhile.dropWhile;

/**
 * Iterate the elements in an Iterable, applying a predicate to each one, returning the first element that
 * matches the predicate, wrapped in an Optional. If no elements match the predicate, the result is
 * Optional.empty(). This function short-circuits, and so is safe to use on potentially infinite
 * Iterables that guarantee to have an eventually matching element.
 *
 * @param  the Iterable element type
 */
public final class Find implements Fn2, Iterable, Optional> {

    private Find() {
    }

    @Override
    public Optional apply(Function predicate, Iterable as) {
        return head(dropWhile(((Predicate) predicate::apply).negate(), as));
    }

    public static  Find find() {
        return new Find<>();
    }

    public static  Fn1, Optional> find(Function predicate) {
        return Find.find().apply(predicate);
    }

    public static  Optional find(Function predicate, Iterable as) {
        return Find.find(predicate).apply(as);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy