Skip to content

Instantly share code, notes, and snippets.

@devshorts
Last active December 28, 2015 01:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devshorts/7423807 to your computer and use it in GitHub Desktop.
Save devshorts/7423807 to your computer and use it in GitHub Desktop.
Create stream from iterable in java 8
public class StreamUtil<T>{
public static <T> Stream<T> ofIterable(Iterable<T> iter){
Iterator<T> iterator = iter.iterator();
Stream.Builder<T> builder = Stream.builder();
while(iterator.hasNext()){
builder.add(iterator.next());
}
return builder.build();
}
}
// usage
import java.util.List;
import java.util.concurrent.ExecutionException;
import static java.util.Arrays.asList;
public class Main{
public static void main(String[] arsg) throws InterruptedException, ExecutionException {
List<String> strings = asList("oooo", "ba", "baz", "booo");
System.out.println(StreamUtil.ofIterable(strings).count());
}
}
@scooby
Copy link

scooby commented May 11, 2015

Don't do this. See https://docs.oracle.com/javase/8/docs/api/java/util/stream/StreamSupport.html , which converts a Spliterator. Iterable (now) has a default method spliterator, so all you need is StreamSupport.stream(iterable.spliterator()). In addition, this technique is lazy, whereas populating a builder requires walking the full Iterable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment