Skip to content

Instantly share code, notes, and snippets.

@thinkbigthings
Created July 28, 2020 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkbigthings/29a6c08cc2847d0810c5bcc6c07dbd68 to your computer and use it in GitHub Desktop.
Save thinkbigthings/29a6c08cc2847d0810c5bcc6c07dbd68 to your computer and use it in GitHub Desktop.
Some functional utilities in Java
public class Functional {
@FunctionalInterface
public interface CheckedFunction<T, R> {
R apply(T t) throws Exception;
}
public static <T, R> Function<T, R> uncheck(CheckedFunction<T, R> checkedFunction) {
return t -> {
try {
return checkedFunction.apply(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
public static <F, T> Function<Collection<F>, List<T>> forList(Function<F,T> elementFunction) {
return collection -> collection.stream().map(elementFunction).collect(toList());
}
public static <K,V> Map<K,V> reduceMap(Map<K,V> m1, Map<K,V> m2) {
m1.putAll(m2);
return m1;
}
/**
* Use this when having more than one element in the stream would be an error.
*
* Optional&lt;User&gt; resultUser = users.stream()
* .filter(user -&gt; user.getId() == 100)
* .collect(findOne());
*
* @param <T> Type
* @return Collection
*/
public static <T> Collector<T, ?, Optional<T>> toOne() {
return Collectors.collectingAndThen(
Collectors.toList(),
list -> {
if (list.size() > 1) {
throw new IllegalStateException("Must have zero or one element, found " + list.size());
}
return list.size() == 1 ? Optional.of(list.get(0)) : Optional.empty();
}
);
}
/**
* Use this when not having exactly one element in the stream would be an error.
*
* Usage:
*
* User resultUser = users.stream()
* .filter(user -&gt; user.getId() == 100)
* .collect(findExactlyOne());
*
* @param messages optional message to show if not finding the expected number of elements
* @param <T> Type
* @return exactly one element.
*/
public static <T> Collector<T, ?, T> toExactlyOne(String... messages) {
return Collectors.collectingAndThen(
Collectors.toList(),
list -> {
if (list.size() != 1) {
String m = "Must have exactly one element, found " + list + ". " + join(", ", asList(messages));
throw new IllegalStateException(m);
}
return list.get(0);
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment