Created
July 1, 2018 13:13
-
-
Save disc99/9fc50b1e107cbcad41ac534f7d34bd3e to your computer and use it in GitHub Desktop.
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
import java.util.Collection; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Optional; | |
import java.util.concurrent.atomic.AtomicReference; | |
import java.util.function.BiFunction; | |
import java.util.function.Function; | |
import java.util.stream.Collector; | |
import static java.util.stream.Collectors.*; | |
public class Functions { | |
public static <T, R> Collector<T, ?, R> toListAnd(Function<List<T>, R> finisher) { | |
return collectingAndThen(toList(), finisher); | |
} | |
public static <T, K, D, R> Collector<T, ?, R> groupingAnd(Function<? super T, ? extends K> classifier, | |
Function<List<T>, D> mapper, | |
Function<List<D>, R> finisher) { | |
return collectingAndThen(groupMappingBy(classifier, toListAnd(mapper)), finisher); | |
} | |
private static <T, K, A, D> Collector<T, ?, List<D>> groupMappingBy(Function<? super T, ? extends K> classifier, | |
Collector<? super T, A, D> downstream) { | |
return collectingAndThen(groupingBy(classifier, downstream), Functions::mapToList); | |
} | |
private static <K, V> List<V> mapToList(Map<K, V> programs) { | |
return programs.entrySet().stream() | |
.map(Map.Entry::getValue) | |
.collect(toList()); | |
} | |
public static <T, U> U reduce(Collection<T> collection, U identity, BiFunction<T, U, U> mapper) { | |
U result = identity; | |
for (T element : collection) { | |
result = mapper.apply(element, result); | |
} | |
return result; | |
} | |
public static <T> Collector<T, ?, Optional<T>> toOptional() { | |
return Collector.<T, AtomicReference<T>, Optional<T>>of( | |
AtomicReference::new, | |
(acc, t) -> acc.compareAndSet(null, t), | |
(a, b) -> { | |
a.compareAndSet(null, b.get()); | |
return a; | |
}, | |
acc -> Optional.ofNullable(acc.get()), | |
Collector.Characteristics.CONCURRENT | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment