Created
May 7, 2024 17:21
-
-
Save yaauie/4de34782781919d443785003b353d5f2 to your computer and use it in GitHub Desktop.
A Collector that uses an intermediate Stream.Builder to collect to a new stream, ensuring that the source stream has been fully consumed.
This file contains hidden or 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
package net.biesemeyer.streams; | |
import java.util.Set; | |
import java.util.function.BiConsumer; | |
import java.util.function.BinaryOperator; | |
import java.util.function.Function; | |
import java.util.function.Supplier; | |
import java.util.stream.Collector; | |
import java.util.stream.Stream; | |
public class StreamCollectors { | |
private StreamCollectors() { } | |
public static <T> Collector<T, Stream.Builder<T>, Stream<T>> toStream() { | |
return new ToStreamCollector<>(); | |
} | |
static class ToStreamCollector<T> implements Collector<T, Stream.Builder<T>, Stream<T>> { | |
@Override | |
public Supplier<Stream.Builder<T>> supplier() { | |
return Stream::builder; | |
} | |
@Override | |
public BiConsumer<Stream.Builder<T>, T> accumulator() { | |
return Stream.Builder::accept; | |
} | |
@Override | |
public BinaryOperator<Stream.Builder<T>> combiner() { | |
return (left,right) -> { | |
right.build().forEach(left); | |
return left; | |
}; | |
} | |
@Override | |
public Function<Stream.Builder<T>, Stream<T>> finisher() { | |
return Stream.Builder::build; | |
} | |
@Override | |
public Set<Characteristics> characteristics() { | |
return Set.of(Characteristics.CONCURRENT, Characteristics.UNORDERED); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment