Java Reference
In-Depth Information
You created a List<Integer> and called its stream() method to get a stream object in Listing 13-1. You can
rewrite that example using the Stream.of() method as follows:
import java.util.stream.Stream;
...
// Compute the sum of the squares of all odd integers in the list
int sum = Stream.of(1, 2, 3, 4, 5)
.filter(n -> n % 2 == 1)
.map(n -> n * n)
.reduce(0, Integer::sum);
System.out.println("Sum = " + sum);
Sum = 35
Note that the second version of the of() method takes a varargs argument and you can use it to create a stream
from an array of objects as well. The following snippet of code creates a stream from a String array.
String[] names = {"Ken", "Jeff", "Chris", "Ellen"};
// Creates a stream of four strings in the names array
Stream<String> stream = Stream.of(names);
the Stream.of() method creates a stream whose elements are of reference type. If you want to create a
stream of primitive values from an array of primitive type, you need to use the Arrays.stream() method that will be
explained shorty.
Tip
The following snippet of code creates a stream of strings from a String array returned from the split() method
of the String class:
String str = "Ken,Jeff,Chris,Ellen";
// The stream will contain fur elements: "Ken", "Jeff", "Chris", and "Ellen"
Stream<String> stream = Stream.of(str.split(","));
The Stream interface also supports creating a stream using the builder pattern using the Stream.Builder<T>
interface whose instance represents a stream builder. The builder() static method of the Stream interface returns a
stream builder.
// Gets a stream builder
Stream.Builder<String> builder = Stream.builder();
The Stream.Builder<T> interface contains the following methods:
void accept(T t)
Stream.Builder<T> add(T t)
Stream<T> build()
 
Search WWH ::




Custom Search