Table of Contents
In this post, we will see about Java 8 Stream‘s of method example.
stream‘s of method is static method and used to create stream of given type.
For example:
1 2 3 4 |
Stream<String> stringStream=Stream.of("India","China","Bhutan","Nepal"); Stream<Integer> integerStream=Stream.of(1,2,3,4,5); |
There are two overloaded version of Stream’s of method.
1) static <T> Stream<T> of(T… values)
Returns a sequential ordered stream whose elements are the specified values.
2) static <T> Stream<T> of(T t)
Returns a sequential Stream containing a single element.
Java Stream of example
Create a class named Java8StreamOfExample as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; import java.util.stream.Stream; public class Java8StreamOfExample { public static void main(String[] args) { Stream<String> stringStream=Stream.of("India","China","Bhutan","Nepal"); stringStream.forEach((e) -> System.out.println(e)); } } |
When you run above program, you will get below output:
India
China
Bhutan
Nepal
China
Bhutan
Nepal
Another example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog.flatMap; import java.util.stream.Stream; public class Java8StreamOfExample { public static void main(String[] args) { Stream<Double> doubleStream=Stream.of(2.0,3.4,4.3); doubleStream. map(e -> 2*e) .forEach((e) -> System.out.println(e)); } } |
When you run above program, you will get below output:
4.0
6.8
8.6
6.8
8.6
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.