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

com.jnape.palatable.lambda.functions.builtin.fn1.Head Maven / Gradle / Ivy

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

import com.jnape.palatable.lambda.adt.Maybe;
import com.jnape.palatable.lambda.functions.Fn1;

import java.util.Iterator;

import static com.jnape.palatable.lambda.adt.Maybe.just;
import static com.jnape.palatable.lambda.adt.Maybe.nothing;

/**
 * Retrieve the head element of an {@link Iterable}, wrapped in an {@link Maybe}. If the {@link Iterable} is empty, the
 * result is {@link Maybe#nothing()}.
 *
 * @param  the Iterable element type
 */
public final class Head implements Fn1, Maybe> {

    private static final Head INSTANCE = new Head<>();

    private Head() {
    }

    @Override
    public Maybe checkedApply(Iterable as) {
        Iterator iterator = as.iterator();
        return iterator.hasNext() ? just(iterator.next()) : nothing();
    }

    @SuppressWarnings("unchecked")
    public static  Head head() {
        return (Head) INSTANCE;
    }

    public static  Maybe head(Iterable as) {
        return Head.head().apply(as);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy