Last active
December 28, 2015 01:49
-
-
Save devshorts/7423807 to your computer and use it in GitHub Desktop.
Create stream from iterable in java 8
This file contains 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
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()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.