The Stream API, introduced in Java 8, it is used to process collections of objects. Stream is a sequence of objects, that supports many different methods which can be pipe lined to produce the desired result.
The features of Java stream are –
- A stream is not a data structure alternatively it takes input from the Collections, Arrays or I/O channels.
- A Streams does not change the original data structure, they only provide the result as the pipelined methods.
- Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipe lined. Terminal operation mark the end of the stream and return the result.
Different way to create Streams:
- Using Collection
Approach:
- Get the collection
- Construct a Sequential Stream from the collection using Collection.stream() method
- Print the Stream
Below is the implementation of the above approach:
Program:
import java.util.*;
import java.util.stream.Stream;
class GFG {
private static <T> void getStream(List<T> list)
{
Stream<T> stream = list.stream();
Iterator<T> it = stream.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " " );
}
}
public static void main(String[] args)
{
List<String> list = new ArrayList<>();
list.add( "Geeks" );
list.add( "for" );
list.add( "Geeks" );
getStream(list);
}
}
|
- Create a stream from specified values
Stream.of(T…t) method can be used to create a stream with the specified t values, where t are the elements. This method returns a sequential Stream containing the t elements.
Below is the implementation of the above approach:
Program:
import java.util.*;
import java.util.stream.Stream;
class GFG {
private static void getStream()
{
Stream<Integer> stream
= Stream.of( 1 , 2 ,
3 , 4 ,
5 , 6 ,
7 , 8 ,
9 );
stream.forEach(p -> System.out.print(p + " " ));
}
public static void main(String[] args)
{
getStream();
}
}
|
Output:
1 2 3 4 5 6 7 8 9
- Create stream from an array:
The Stream.of() and Arrays.stream() are two commonly used methods for creating a sequential stream from a specified array. Both these methods returns a Stream when called with a non-primitive type T.
Integer array
- Create stream using Arrays.stream()
Program:
import java.util.*;
import java.util.stream.Stream;
class GFG {
private static <T> void getStream(T[] arr)
{
Stream<T> streamOfArray
= Arrays.stream(arr);
Iterator<T> it
= streamOfArray.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " " );
}
}
public static void main(String[] args)
{
String[] arr
= new String[] { "a" , "b" , "c" };
getStream(arr);
}
}
|
- Create stream using Stream.of()
A non interfering action to be perform on elements as they are consumed from the stream and returns also a new stream.
Program:
import java.util.*;
import java.util.stream.Stream;
class GFG {
private static <T> void getStream(T[] arr)
{
Stream<T> streamOfArray = Stream.of(arr);
Iterator<T> it = streamOfArray.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " " );
}
}
public static void main(String[] args)
{
String[] arr
= new String[] { "a" , "b" , "c" };
getStream(arr);
}
}
|
- Create an empty stream using Stream.empty()
The empty() method is used upon creation to avoid returning null for streams with no element.
Program:
import java.util.*;
import java.util.stream.Stream;
class GFG {
private static void getStream()
{
Stream<String> streamOfArray
= Stream.empty();
Iterator<String> it
= streamOfArray.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " " );
}
}
public static void main(String[] args)
{
getStream();
}
}
|
- Create a Stream using Stream.builder()
The builder() method is used when the desired type should be additionally specified in the right part of the statement, otherwise the build() method will create an instance of the Stream.
Program:
import java.util.*;
import java.util.stream.Stream;
class GFG {
private static <T> void getStream()
{
Stream.Builder<String> builder
= Stream.builder();
Stream<String> stream = builder.add( "a" )
.add( "b" )
.add( "c" )
.build();
Iterator<String> it = stream.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " " );
}
}
public static void main(String[] args)
{
getStream();
}
}
|
- Create an infinite Stream using Stream.iterate()
The iterate() method returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed. In below example, First element of the resulting stream is a first parameter of the iterate method. For creating every following element the function is applied to the previous element. In the example below the second element will be 4.
Program:
import java.util.*;
import java.util.stream.Stream;
class GFG {
private static <T> void
getStream( int seedValue, int limitTerms)
{
Stream.iterate(seedValue,
(Integer n) -> n * n)
.limit(limitTerms)
.forEach(System.out::println);
}
public static void main(String[] args)
{
int seedValue = 2 ;
int limitTerms = 5 ;
getStream(seedValue, limitTerms);
}
}
|
- Create an infinite Stream using Stream.generate() method
The generate() method accepts a Supplier for generating elements and the resulting stream is infinite. So to restrict it, specify the desired size or the generate() method will work until it reaches the memory limit.
Program:
import java.util.*;
import java.util.stream.*;
class GFG {
private static <T> void getStream( int limitTerms)
{
Stream.generate(Math::random)
.limit(limitTerms)
.forEach(System.out::println);
}
public static void main(String[] args)
{
int limitTerms = 5 ;
getStream(limitTerms);
}
}
|
Output:
0.2293502475696314
0.5650334795948209
0.3418138293253522
0.36831074763500116
0.4864408670097241
- Create stream from a Pattern using Predicate
In java 8, the Predicate asPredicate() method of Pattern creates a predicate boolean-valued function that is used for pattern matching.
Program:
import java.util.*;
import java.util.stream.*;
import java.util.regex.Pattern;
class GFG {
private static void
getStream(List<String> list, Pattern p)
{
list.stream()
.filter(p.asPredicate())
.forEach(System.out::println);
}
public static void main(String[] args)
{
List<String> list
= Arrays
.asList( "Geeks" ,
"For" ,
"Geek" ,
"GeeksForGeeks" ,
"A Computer Portal" );
Pattern p = Pattern.compile( "^G" );
getStream(list, p);
}
}
|
Output:
Geeks
Geek
GeeksForGeeks
- Create stream from Iterator
Iterators, in Java, are used in Collection Framework to retrieve elements one by one. Spliterator is the key to create the sequential stream. Hence in this method also, Spliterator is used. But in this method, the source of Spliterator is set to an Iterable created from the Iterator. So first the Iterable is created from the Iterator. Then the Spliterator is passed to the stream() method directly as Iterable.spliterator().
Program:
import java.util.*;
import java.util.stream.*;
class GFG {
private static <T> void getStream(Iterator<T> itr)
{
Spliterator<T> spitr
= Spliterators
.spliteratorUnknownSize(itr,
Spliterator.NONNULL);
Stream<T> stream
= StreamSupport.stream(spitr, false );
Iterator<T> it = stream.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " " );
}
}
public static void main(String[] args)
{
Iterator<String> iterator = Arrays
.asList( "a" , "b" , "c" )
.iterator();
getStream(iterator);
}
}
|
- Create stream from Iterable
Iterable interface is designed keeping in mind and does not provide any stream() method on its own. Simply it can be passed into StreamSupport.stream() method, and get a Stream from the given Iterable object. It is easier to turn an Iterable into a Stream. Iterable has a default method spliterator(), which can be used to get a Spliterator instance, which can be in turn then converted to a Stream.
Note: The Iterable is not a instance of Collection, this method internally calls StreamSupport.stream() to get a sequential Stream from Spliterator else it simply calls Collection.stream() method.
Program:
import java.util.*;
import java.util.stream.*;
class GFG {
private static <T> void getStream(Iterable<T> iterable)
{
Stream<T> stream
= StreamSupport
.stream(iterable.spliterator(),
false );
Iterator<T> it = stream.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " " );
}
}
public static void main(String[] args)
{
Iterable<String> iterable
= Arrays.asList( "a" , "b" , "c" );
getStream(iterable);
}
}
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!