Skip to content

Commit

Permalink
Merge pull request #5 from gm2211/feature/stream-from-iterator
Browse files Browse the repository at this point in the history
1. Added public method to MoreStream to create a new stream from an i…
  • Loading branch information
j-baker committed Mar 21, 2016
2 parents dc5470c + 9918041 commit 520cde8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@ Each map function also accepts a [BiFunction], making it easy to modify keys bas

* [Iterables][Iterable] (equivalent to the wordy `StreamSupport.stream(iterable.spliterator(), false)`)
* [Optionals][] (equivalent to `optionalValue.map(Stream::of).orElse(Stream.of())`)
* [Iterators][Iterator] (equivalent to `StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);`)

[BiFunction]: https://docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html
[Iterable]: https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html
[Iterator]: https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
[Map]: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
[Optionals]: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
[Stream]: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
15 changes: 15 additions & 0 deletions src/main/java/com/palantir/common/streams/MoreStreams.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
*/
package com.palantir.common.streams;

import java.util.Iterator;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

Expand Down Expand Up @@ -43,5 +46,17 @@ public static <T> Stream<T> stream(Optional<T> optionalValue) {
return optionalValue.map(Stream::of).orElse(Stream.of());
}

/**
* Returns a stream from the provided iterator, preserving the iteration order.
*
* @param iterator Iterator for which a stream needs to be created
* @param <T> Type parameter for the iterator
* @return A stream for the iterator
*/
public static <T> Stream<T> stream(Iterator<T> iterator) {
Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED);
return StreamSupport.stream(spliterator, NOT_PARALLEL);
}

private MoreStreams() {}
}

0 comments on commit 520cde8

Please sign in to comment.