BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java 8 Stream Tutorial

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

In the previous tutorial we learned the interface changes in java 8. In this guide, we will discuss Stream API which is another new feature of java 8. All the classes and interfaces of this API is in the java.util.stream package. By using streams we can perform various aggregate operations on the data returned from collections, arrays, Input/Output operations. Before we see how stream API can be used in Java, let’s see an example to understand the use of streams.

Java Stream Example

To understand how stream works, lets take an example without using stream and then we will see the same example with streams.

Finding certain strings without using Stream

import java.util.ArrayList;
import java.util.List;
public class Example{ 
   public static void main(String[] args) {    
	List<String> names = new ArrayList<String>();
	names.add("Ajeet");
	names.add("Negan");
	names.add("Aditya");
	names.add("Steve");
	int count = 0;
	for (String str : names) {
	   if (str.length() < 6) 
		count++; 
	}
        System.out.println("There are "+count+" strings with length less than 6");
   }  
}

Output:

There are 3 strings with length less than 6

Same example using Stream

import java.util.ArrayList;
import java.util.List;
public class Example{ 
   public static void main(String[] args) {    
	List<String> names = new ArrayList<String>();
	names.add("Ajeet");
	names.add("Negan");
	names.add("Aditya");
	names.add("Steve");
		
	//Using Stream and Lambda expression
	long count = names.stream().filter(str->str.length()<6).count();
	System.out.println("There are "+count+" strings with length less than 6");

   }  
}

Output:

There are 3 strings with length less than 6

What is the difference between these codes?
The output of both the examples are same, however there is a major difference between these examples if you consider the performance of the code.
In the first example, we are iterating the whole list to find the strings with length less than 6. There is no parallelism in this code.
In the second example, the stream() method returns a stream of all the names, the filter() method returns another stream of names with length less than 6, the count() method reduces this stream to the result. All these operations are happening parallelly which means we are able to parallelize the code with the help of streams. Parallel execution of operations using stream is faster than sequential execution without using streams.

How to work with Stream in Java

As we have seen in the above example, the working of stream can be explained in three stages:
1. Create a stream

2. Perform intermediate operations on the initial stream to transform it into another stream and so on on further intermediate operations. In the above example, the filter() operation is intermediate operation, there can be more than one intermediate operations.

3. Perform terminal operation on the final stream to get the result. In the above example, the count() operation is terminal operation.

Java Stream Features

1. Stream does not store the elements. it simply performs the aggregate operations(such as filter() and count() that we have seen in the above example) to get the desired stream of data.

2. The aggregate operations that we perform on the collection, array or any other data source do not change the data of the source, they simply return a new stream. For example the code we have seen above is filtering the strings with length less than 6 using the stream operations but it didn’t change the elements of the list.

3. All the stream operations are lazy in nature which means they are not executed until they are needed. For example, if we want to display only the first 2 elements of a list using stream, the stream operation would stop at the end of second iteration after displaying the second element of list.

Let’s see few examples of Java Stream:

Java Stream Example 1: Iterating and displaying selected integers

import java.util.stream.*;  
public class Example {  
    public static void main(String[] args){  
        Stream.iterate(1, count->count+1)  
        .filter(number->number%3==0)  
        .limit(6)  
        .forEach(System.out::println);  
    }  
}

Output:

3
6
9
12
15
18

Java Stream Example 2: Concatenating two streams

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Example {
   public static void main(String[] args) {
	//list 1
	List<String> alphabets = Arrays.asList("A","B","C");
	//list 2
	List<String> names = Arrays.asList("Sansa","Jon","Arya");
		
	//creating two streams from the two lists and concatenating them into one
	Stream<String> opstream = Stream.concat(alphabets.stream(), names.stream());
		
	//displaying the elements of the concatenated stream
	opstream.forEach(str->System.out.print(str+" "));
   }
}

Output:

A B C Sansa Jon Arya

Related Posts:

  1. Java Stream allMatch() Example
  2. Java Stream noneMatch() Example
  3. Java Stream anyMatch() example
❮ PreviousNext ❯

Top Related Articles:

  1. Java 8 Interface Changes – default method and static method
  2. Java 9 – @SafeVarargs Annotation (with examples)
  3. Java 8 Stream Filter with examples
  4. Java 8 – Filter a Map by keys and values
  5. Java 8 forEach method with example

Tags: Java8-Features

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap