Created
July 28, 2020 09:31
-
-
Save thinkbigthings/29a6c08cc2847d0810c5bcc6c07dbd68 to your computer and use it in GitHub Desktop.
Some functional utilities in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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<User> resultUser = users.stream() | |
* .filter(user -> 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 -> 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