Created
September 11, 2016 19:13
-
-
Save fagossa/97814255e5959d823bb6608445d792e8 to your computer and use it in GitHub Desktop.
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
| class SpliteratorExample { | |
| private static class GroupSpliterator<T> implements Spliterator<Stream<T>> { | |
| private final int grouping; | |
| private final Spliterator<T> spliterator; | |
| GroupSpliterator(int grouping, Spliterator<T> spliterator) { | |
| this.grouping = grouping; | |
| this.spliterator = spliterator; | |
| } | |
| @Override | |
| public boolean tryAdvance(Consumer<? super Stream<T>> action) { | |
| Stream.Builder<T> builder = Stream.builder(); | |
| boolean finished = false; | |
| for (int i = 0; i < grouping; i++) { | |
| if (spliterator.tryAdvance(builder::add)) { | |
| finished = true; | |
| } | |
| } | |
| final Stream<T> subStream = builder.build(); | |
| action.accept(subStream); | |
| return !finished; | |
| } | |
| @Override | |
| public Spliterator<Stream<T>> trySplit() { | |
| final Spliterator<T> aNewSpliterator = this.spliterator.trySplit(); | |
| return new GroupSpliterator<T>(grouping, aNewSpliterator); | |
| } | |
| @Override | |
| public long estimateSize() { | |
| return spliterator.estimateSize() / grouping; | |
| } | |
| @Override | |
| public int characteristics() { | |
| return this.spliterator.characteristics(); | |
| } | |
| } | |
| public static void main(String... args) { | |
| final List<String> data = Arrays.asList("1", "2", "3", "4", "5", "6"); | |
| final GroupSpliterator<String> spliterator = new GroupSpliterator<>(3, data.spliterator()); | |
| final Stream<Stream<String>> stream = StreamSupport.stream(spliterator, false); | |
| // transform the nested stream into collection | |
| final List<List<String>> groupedData = stream.collect(Collectors.toList()) | |
| .stream() | |
| .map(subStream -> subStream.collect(Collectors.toList())) | |
| .collect(Collectors.toList()); | |
| // print result | |
| groupedData.forEach(list -> { | |
| final String joined = list.stream().collect(Collectors.joining(" ")); | |
| System.out.println("[" + joined + "]"); | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment