Home  >  Java 8

Java Stream.of() Example

By Arvind Rai, May 30, 2020
This page will walk through Java Stream.of method example. The Stream.of is used to create sequential streams for the given elements. We can pass a single element or multiple elements to Stream.of method.
Find the Stream.of method declarations from Java doc.
1.
static <T> Stream<T> of(T t) 
Parameters: Pass a single element.
Returns: The method returns a stream with one element.

2.
static <T> Stream<T> of(T... values) 
Parameters: Pass the elements of the new stream.
Returns: The method returns a stream containing the given elements.

The Stream.of creates a stream of finite elements. To create a stream of infinite elements, we can use Stream.generate method.
Now find some examples of Stream.of method.

Example-1
Let us create the stream of integers.
Stream<Integer> mystream = Stream.of(10, 12, 14, 16); 
Suppose we iterate and print the stream elements.
mystream.forEach(e -> System.out.println(e)); 
The output will be 10 12 14 16.

Example-2
Let us create stream of string.
Stream<String> mystream = Stream.of("AA", "BB", "CC", "DD");
mystream.forEach(e -> System.out.println(e)); 
The output will be AA BB CC DD.

Example-3
Find the example to create the stream of objects.
StreamOfObjDemo.java
package com.concretepage;
import java.util.stream.Stream;
public class StreamOfObjDemo {
  public static void main(String[] args) {
	Stream<User> userStream = Stream.of(
		new User("Mahesh", 22),
		new User("Krishn", 20),
		new User("Suresh", 25)
	);
	userStream.forEach(u -> System.out.println(u.getUserName()));
  }
}
class User {
  private String userName;
  private int age;
  public User(String userName, int age) {
	this.userName = userName;
	this.age = age;
  }
  //Sets and Gets
} 
Output
Mahesh
Krishn
Suresh 

Example-4
To create IntStream, we use IntStream.of method.
To create LongStream, we use LongStream.of method.
To create DoubleStream, we use DoubleStream.of method.
Find the examples.
StreamOfDemo.java
package com.concretepage;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class StreamOfDemo {
  public static void main(String[] args) {
	System.out.println("--- IntStream ---");
	IntStream intStream = IntStream.of(12, 14, 16);
	intStream.forEach(e -> System.out.println(e));
	
	System.out.println("--- LongStream ---");	
	LongStream longStream = LongStream.of(154L, 236L, 306L);
	longStream.forEach(e -> System.out.println(e));
	
	System.out.println("--- DoubleStream ---");	
	DoubleStream doubleStream = DoubleStream.of(123.56, 456.87, 784.65);
	doubleStream.forEach(e -> System.out.println(e));	
  }
} 
Output
--- IntStream ---
12
14
16
--- LongStream ---
154
236
306
--- DoubleStream ---
123.56
456.87
784.65 

Reference

Java doc: Stream
POSTED BY
ARVIND RAI
ARVIND RAI








©2020 concretepage.com | Privacy Policy | Contact Us