Java Reference
In-Depth Information
How would you generate an infinite stream of a repeating value? For example, how would you generate an
infinite stream of zeroes? The following snippet of code shows you how to do this:
IntStream zeroes = IntStream.generate(() -> 0);
Streams from Arrays
The Arrays class in the java.util package contains an overloaded stream() static method to create sequential
streams from arrays. You can use it to create an IntStream from an int array, a LongStream from a long array, a
DoubleStream from a double array, and a Stream<T> from an array of the reference type T . The following snippet of
code creates an IntStream and a Stream<String> from an int array and a String array:
// Creates a stream from an int array with elements 1, 2, and 3
IntStream numbers = Arrays.stream(new int[]{1, 2, 3});
// Creates a stream from a String array with elements "Ken", and "Jeff"
Stream<String> names = Arrays.stream(new String[] {"Ken", "Jeff"});
You can create a stream from a reference type array using two methods: Arrays.stream(T[] t) and
Stream.of(T...t) method. providing two methods in the library to accomplish the same thing is intentional.
Tip
Streams from Collections
The Collection interface contains the stream() and parallelStream() methods that create sequential and parallel
streams from a Collection , respectively. The following snippet of code creates streams from a set of strings:
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
...
// Create and populate a set of strings
Set<String> names = new HashSet<>();
names.add("Ken");
names.add("jeff");
// Create a sequential stream from the set
Stream<String> sequentialStream = names.stream();
// Create a parallel stream from the set
Stream<String> parallelStream = names.parallelStream();
Streams from Files
Java 8 has added many methods to the classes in the java.io and java.nio.file packages to support I/O operations
using streams. For example,
You can read text from a file as a stream of strings in which each element represents one line of
text from the file.
JarEntry from a JarFile .
You can obtain a stream of
 
 
Search WWH ::




Custom Search