Site icon JavaGoal

Stream in Java 8

Here is the table content of the article will we will cover this topic.
1. What is Stream in Java?
2. What is the need of Stream?
3. How Does Stream work in Java?
4. How to Create a Stream?
5. Stream operations in java?
6. Intermediate operation in Java 8?
7. Terminal operations in java 8?
8. Short circuit operations in Java 8?
9. Lazy evaluation of stream?
10. Converting stream to collections and Arrays?

Stream in Java is the major functionality of Java 8. In this tutorial, we will read how to create a Stream and how it works. To understand the functionality of Stream you need some basic knowledge of Functional interface, Lambda expression, optional and method reference.

What is Stream in Java?

A Stream in Java is a sequence of objects that provide a various method which helps to produce the desired result. The Stream takes data from a source that supports aggregate operations on them. Collections and Arrays are the sources of Stream. It presents in java.util.stream

Important points about Stream:
1. Stream maintains the order of data as it is in the source.
2. Streams allow us to make bulk manipulation in with convenient way.
3. Stream doesn’t make any modifications to the source.
4. Stream doesn’t store the data, It’s not a data structure.
5. It uses Collections, Arrays or I/O channels as a source of data.
6. Streams have many intermediate operations that return the result as a stream. These are known as lazily executed. Its also known as pipelining.
7. That operation returns the result is known as terminal operation.

What is the need of Streams in java?

Before the creation of Stream let’s understand the concept of Stream for example. We will discuss why Stream is required.

Suppose we have a list of String and we want to print each string in capital letters. We need to do a few steps:
1. We just want to make capital all the string of lists. So, we must iterate the list.
2. Getting each string and applying an operation to it.
3. There is a lot of code to do for a simple task.

import java.util.Arrays;
import java.util.List;
public class ExampleOfWithoutStream 
{
    public static void main(String[] args) 
    {
    	List<String> list = Arrays.asList("a", "b", "c", "d", "e");
    	for(String s : list)
    		System.out.println(s.toUpperCase());
    }	
}

Output: A
B
C
D
E

In java 8, By use of Stream, We can do all the steps in one with effective and clear code.

import java.util.Arrays;
import java.util.List;
public class ExampleOfStream 
{
    public static void main(String[] args) 
    {
    	List<String> list = Arrays.asList("a", "b", "c", "d", "e");
    	list.stream().forEach((a) -> System.out.println(a.toUpperCase()));
    }	
}

Output: A
B
C
D
E

How Does Stream work in Java?

As you can see in the above example, we are working with the stream in Java.
The working of Stream is divided into steps:
Step1: You must have to create a stream before use.
Step 2: You can perform intermediate operations or terminal operations on the initial stream. We will discuss it later.

How to Create a Stream?

You can create a stream in several ways from arrays and collections. Let’s investigate these with simple examples.

1. Stream.of(): This method returns the stream that is a sequential ordered stream whose elements are the specified values. You can obtain a stream by simply use of the source. For example, here we are getting a stream by Arrays and List.
NOTE: You can’t use any primitive data type. It doesn’t support autoboxing.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ExampleOfStream 
{
    public static void main(String[] args) 
    {
    	String list[] = new String[]{"A", "B", "C", "D", "E"};
    	
    	// Creating Stream from String Array
    	Stream<String> stream = Stream.of(list);
    	stream.forEach(s -> System.out.println(s.toLowerCase()));
    	
    	List<Integer> listOfInt = Arrays.asList(1,2,3,4,5);
    	// Creating Stream from ArrayList
    	Stream<List<Integer>> stream1 = Stream.of(listOfInt);
    	stream1.forEach(a -> System.out.println(a));
    	    
    }	
}

Output: a
b
c
d
e
[1, 2, 3, 4, 5]

2. Stream(): This method returns the sequential stream of the source. It is a default method of Collection Interface.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class ExampleOfStream 
{
    public static void main(String[] args) 
    {
    	List<Integer> intList = new ArrayList<>();
    	for(int i=0; i<10; i++) 
    		intList.add(i);
    			
    	//Creating a sequential stream from ArrayList
    	Stream<Integer> sequentialStream = intList.stream();
    	sequentialStream.forEach(System.out::println);
    }	
}

Output: 0
1
2
3
4
5
6
7
8
9

3. parallelStream(): This method returns the parallel stream of the source. It is a default method of Collection Interface.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class ExampleOfStream 
{
    public static void main(String[] args) 
    {
    	List<Integer> intList = new ArrayList<>();
    	for(int i=0; i<10; i++) 
    		intList.add(i);
    			
    	//Creating a sequential stream from ArrayList
    	Stream<Integer> sequentialStream = intList.stream();
    	sequentialStream.forEach(System.out::println);
    }	
}

Output: 6
5
1
2
8
4
3
9
7
0

4. generate(Supplier<? extends T> s): This method generates an infinite sequential unordered stream. It accepts the supplier and generates a stream where each element is generated from the specified Supplier

import java.util.stream.Stream;
public class ExampleOfStream 
{
    public static void main(String[] args) 
    {
    	// Generating a stream by use of Predicate
    	Stream<String> stream = Stream.generate(() -> "Hi");
        stream.forEach((a) -> System.out.println(a));  
    }	
}

Output: Hi
Hi
Hi

5. stream(T[] array): This method is used for a stream from Array. It returns a sequential stream from the source.

import java.util.Arrays;
import java.util.stream.Stream;
public class ExampleOfStream 
{
    public static void main(String[] args) 
    {
    	Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4});
        stream.forEach((a) -> System.out.println(a));
    }	
}

Output: 1
2
3
4

6. IntStream chars(): This method is used for a stream from String. It returns an IntStream from the source.

import java.util.stream.IntStream;
public class ExampleOfStream 
{
    public static void main(String[] args) 
    {
    	IntStream stream = "Hello".chars();
        stream.forEach((a) -> System.out.println(a));
    }	
}

Output: 72
101
108
108
111

Exit mobile version