com.jnape.palatable.lambda.functions.builtin.fn1.Head Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of lambda Show documentation
Show all versions of lambda Show documentation
Functional patterns for Java
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