Skip to content

Instantly share code, notes, and snippets.

@americanstone
Created January 24, 2018 02:49
Show Gist options
  • Save americanstone/f7bea8bcb9534e84495b5cb97f762f07 to your computer and use it in GitHub Desktop.
Save americanstone/f7bea8bcb9534e84495b5cb97f762f07 to your computer and use it in GitHub Desktop.
Adding two streams, or an extra element to a stream
Stream<Foo> stream = stream1.collect(concat(stream2)).collect(concat(element));
Stream<Foo> stream = stream1
.filter(x -> x!=0)
.collect(concat(stream2))
.filter(x -> x!=1)
.collect(concat(element))
.filter(x -> x!=2);
private static <T,A,R,S> Collector<T,?,S> combine(Collector<T,A,R> collector, Function<? super R, ? extends S> function) {
return Collector.of(
collector.supplier(),
collector.accumulator(),
collector.combiner(),
collector.finisher().andThen(function));
}
public static <T> Collector<T,?,Stream<T>> concat(Stream<? extends T> other) {
return combine(Collectors.toList(),
list -> Stream.concat(list.stream(), other));
}
public static <T> Collector<T,?,Stream<T>> concat(T element) {
return concat(Stream.of(element));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment