Create Streams from Values
Description
We can use of()
from Stream interface
to create a sequential Stream from a single value and multiple values .
<T> Stream<T> of(T t)
<T> Stream<T> of(T...values)
From the method signature we can see that the first of() method creates a stream from a single value while the second of() method creates a stream from varied length parameters
Example
The following code creates a stream which contains a single value.
import java.util.stream.Stream;
// w ww . j a v a 2 s. c o m
public class Main {
public static void main(String[] args) {
Stream<String> stream = Stream.of("java2s.com");
stream.forEach(System.out::println);
}
}
The code above generates the following result.
Example 2
The following code creates a stream with four strings.
import java.util.stream.Stream;
//from www . j a v a2 s. c o m
public class Main {
public static void main(String[] args) {
Stream<String> stream = Stream.of("XML", "Java", "CSS", "SQL");
stream.forEach(System.out::println);
}
}
The code above generates the following result.
Example 3
The following code creates a stream from an array of objects.
import java.util.stream.Stream;
/*from w w w. ja v a 2 s. c o m*/
public class Main {
public static void main(String[] args) {
String[] names = { "XML", "Java", "SQL", "CSS" };
Stream<String> stream = Stream.of(names);
stream.forEach(System.out::println);
}
}
The code above generates the following result.