Skip to content

Instantly share code, notes, and snippets.

@gjesse
Last active September 7, 2017 20:27
Show Gist options
  • Save gjesse/2c769246a9a7ade2ac30b60cb21f989a to your computer and use it in GitHub Desktop.
Save gjesse/2c769246a9a7ade2ac30b60cb21f989a to your computer and use it in GitHub Desktop.
package com.lithium.java8.chapter3;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class Advanced {
public static void main(String[] args) {
Stream.of(1, 2, 3, 10, 20)
.reduce(Stream.empty(), filteringAccumulator(x -> x % 2 == 0), Stream::concat)
.reduce(Stream.empty(), mappingAccumulator(x -> x * 2), Stream::concat)
.forEach(System.out::println);
}
static <T> BiFunction<Stream<T>, T, Stream<T>> filteringAccumulator(Predicate<T> filter) {
return (stream, element) -> {
if (filter.test(element)) {
return appendToStream(stream, element);
} else {
return stream;
}
};
}
static <T, R> BiFunction<Stream<R>, T, Stream<R>> mappingAccumulator(Function<T, R> mapper) {
return (stream, element) -> appendToStream(stream, mapper.apply(element));
}
static <R> Stream<R> appendToStream(Stream<R> stream, R element) {
return Stream.concat(stream, Stream.of(element));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment