EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Java 8 Tutorial Java 8 Stream
Secondary Sidebar
Java Technology Tutorial
  • Java 7, Java 8 and Java 9
    • Java 7 Features
    • What's New in Java 8
    • Java 8 Features
    • How to Install Java 8
    • Java 8 Collections
    • Java 8 Collectors
    • Optional Class in Java 8
    • Java 8 Stream
    • Java 8 Interview Questions
    • Java 9 Features
  • Java servlet
    • What is Servlet
    • Servlet API
    • JAX-RS Jersey
    • Svelte Components
    • Java collection cheat sheet
    • Java collection hierarchy
    • Java collection api
    • Servlet Life Cycle
    • ServletContext
    • Servlet Filter
    • Session in Servlet
    • Session Bean
    • Entity Beans
    • Entity Framework Insert
    • What is JDB
    • Java Servlet Interview Questions
    • Servlet Types
    • Servlet Listener
    • Servlet Interview Questions
  • JSP
    • JSP Page
    • JSP if else
    • JSP property
    • JSP request
    • JSP format
    • What is JSP
    • JSP in Java
    • JSP Life Cycle
    • JSP?Architecture?
    • JSP Objects
    • Custom Tags in JSP
    • JSP Tag Library
    • JSP Directives
    • JSP Scripting Elements
    • JSP foreach
    • JSP Checkbox
    • JSP Include
    • JSP Taglib
    • JSP Scriptlet
    • JSP Declaration
    • Servlet JSP
    • JSP Redirect
    • JSP Forward
    • JSP Filters
    • JSP Formatter
    • JSP Expression
    • JSP File
    • Cookies in JSP
    • JSP Login Page
    • JSP Error Page
    • JSP getParameter
    • JSP Session
    • JSP Alert
    • JSP Implicit Objects
    • JSP Interview Questions
  • EJB
    • What is EJB
    • EJB Architecture
    • EJB Interview Questions
  • Java awt
    • What is AWT in Java
    • Java ActionListener
    • Java AWT Controls
    • Java MouseListener
    • Cron Scheduler in Java
    • JavaMail Api
    • Robot Framework with Java
    • Java Mail Properties
    • Java collection set
    • Java WindowListener
    • Java KeyListener
    • Java ItemListener
    • ScrollBar in Java
  • JSF
    • What is JSF
    • JSF Life Cycle
    • JSF Components
    • JSF Validation
    • JSF Interview Questions
  • JPA
    • What is JPA?
    • Java Persistence API
    • JPA Annotations
    • JAX-RS
    • What is ORM?
    • JPQL
  • JSTL
    • What is JSTL
    • JSTL Tags
    • JSTL replace
  • J2EE
    • What is JEE?
    • J2EE Framework
    • J2EE Architecture
  • Struct
    • What is Struts?
    • Struts Framework
    • Struts Architecture
  • Ant
    • Apache Ant
    • RESTful Services
    • Nutch Apache
    • Applet Life Cycle
    • Apache POI Dependency
  • JDBC
    • JDBC Batch Update
    • JDBC Insert
    • JDBC PreparedStatement
    • JDBC MySQL Driver
    • JFreeChart
    • JDBC Update
    • JDBC template
    • JDBC transaction
    • JDBC Types
    • JDBC Batch Insert
    • JDBC getConnection
    • JDBC connector
    • JDBC datasource
    • JDBC fetch size
    • JDBC resultset
    • JDBC Statement

Related Courses

Java Servlet Training Course

JavaFX Training Course

Jmeter Testing Training Course

Java 8 Stream

By Anusua DuttaAnusua Dutta

Java 8 Stream

Introduction to Java 8 Stream

The following article provides an outline for Java 8 Stream. Stream is collection of some elements in an order from source that forms an aggregation where a source can be an array or collections which provides data to the stream. Java 8 streams also work with the same principle which means it is basically a prototype or data structure which will be organized and designed in a sequence to perform and manipulate data needed on demand. These streams are generated but is not visible to the end user which forecasts that it is always performed in the background, not in the foreground, but the activity does exist.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Generation of streams can be performed with collections using two methods of collection interface which is depicted as follows:

List<String> strings = Arrays.asList("abc", "" , "bc", "efgh" , "");
List<String> filtered = Strings.stream().filter(string - > !string.isEmpty()).collect(collectors.toList());

Associated return types are as follows:

  • stream(): It returns a sequence of stream with an order considering collection as a source for the computation.
  • parallelStream(): Returns of parallel stream which also consider collection as its prime root for computation to the list.

It consists of many other methods also which follow the generation of a stream consisting collection those methods include: forEach, map, filter, limit, etc.

How Stream Works in Java 8?

The normal stream concept in Java comprises of Input Stream and Output Stream respectively. But the introduction of the stream concept in java 8 supports and behaves in a different manner. It has its own perspective in terms of computation and manipulation. Streams introduced in Java 8 is a new abstract layer that can process data in a declarative manner like queries being performed for the SQL query or statements.

Difficulty faced by developers using the collection frameworks or any other data structure creates the entire task of performing repeated checks and looping complex. Also, multi-core processors available for writing parallel code in the processor become easy and simplified using the stream of Java8.

Stream in java 8 defines an order and sequence for its data stream. The input is being feeded as an object which supports some operations related to aggregation and composition. These inputs being fed possess some characteristics and they are described below.

Characteristics of Java 8 Stream

Below are the characteristics of Java 8 Stream:

  • Sequencing Stream: All the elements within the stream follows a sequence and an order which computes some elements on demand and never stores those elements in a conventional manner.
  • Source: The data being fed as an input which means the stream takes collections, arrays, or I/O resources.
  • Aggregation and Composition: Aggregation operation is being associated with the stream continuously which includes operations like filter, map, limit, reduce, etc.
  • Iterations in an Automated Manner: Collections involve iteration which requires elements to operate externally but to perform iterations internally it involves and makes use of source elements use to feed in the stream as an input.
  • Pipelining: As its name suggests pipelining is a pattern where the streams generated gets returned by themselves and then they don’t return any output to the target. Moreover, it makes use of an intermediate operation to return the output after some computation. It also includes another method which is collect () method used for termination of the operations on the pipeline for stream generation and is generally found at the end of the entire pipeline flow.

Methods of Java 8 Stream

There are many methods involved for computation of each element of the stream like:

  • For Each: This method is used for iteration of elements of the stream.
  • Filter: The filter method is used to eliminate elements based on some conditions and constraints.
  • Limit: This method is used to reduce the size of the element of the entire stream.
  • Sorted: This method as part of the input stream functions in a way that it is used for sorting the stream in a manner.
  • Parallel Processing: Parallel Processing has an alternative which is Parallel stream and involves an easy switch between the sequential and parallel streams.
  • Collectors: A combination of string is performed for processing of elements of a stream. It also returns a list or a string as a return type.
  • Statistics: This is a special feature in addition to java 8 streaming which is used to calculate all the stream statistics result.

Examples of Java 8 Stream

Given below are the examples of Java 8 Stream:

Example #1

This program is an example to illustrate lists, arrays, and components before performing the Java Stream Expressions.

Code:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Stream_Expression_Java {
public static void main(String[] args) {
List<String> lines = Arrays.asList("Science", "Chemistry", "Maths");
List<String> result = getFilterOutput(lines, "Maths");
for (String temp11 : result) {
System.out.println(temp11);
}
}
private static List<String> getFilterOutput(List<String> lines, String filter) {
List<String> result = new ArrayList<>();
for (String line : lines) {
if (!"Chemistry".equals(line)) {
result.add(line);
}
}
return result;
}
}

Output:

Java 8 Stream Example 1

Example #2

This program illustrates the Java8 Streaming Expressions with a list of components in an array, list, and lists, where the list components get converted into the final output with the help of streaming and filtering.

Code:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Java8StreamingStarted {
public static void main(String[] args) {
List<String> lines = Arrays.asList("Walnut", "Apricot", "almond");
List<String> result = lines.stream()
.filter(line -> !"almond".equals(line))
.collect(Collectors.toList());
result.forEach(System.out::println);
}
}

Output:

Java 8 Stream Example 2

Example #3

This program is used to convert the normal list of Array of alphabets into the uppercase array of alphabets using Java 8 Stream using a map stream of collections.

Code:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class java_8_Stream {
public static void main(String[] args) {
List<String> alphabets = Arrays.asList("p", "q", "r", "s");
List<String> alphabet_Upper = new ArrayList<>();
for (String s : alphabets) {
alphabet_Upper.add(s.toUpperCase());
}
System.out.println(alphabets);
System.out.println(alphabet_Upper);
List<String> collect = alphabets.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(collect);
List<Integer> num = Arrays.asList(3,4,5,6,7,8);
List<Integer> collect1 = num.stream().map(n -> n * 2).collect(Collectors.toList());
System.out.println(collect1);
}
}

Output:

Array of Alphabets Example 3

Conclusion

Unlike the InputStream and OutputStream which functions for Java. Streaming in Java 8 is completely different it makes use of a sequenced data structure which works as an abstract layer and then makes use of Java 8 streaming API which is used for the computation and generation of streams.

Recommended Articles

This is a guide to Java 8 Stream. Here we discuss the introduction and how stream works in Java 8 and its characteristics along with examples. You can also go through our other suggested articles to learn more –

  1. Java Tools
  2. Layout in Java
  3. Java Compilers
  4. Merge Sort In Java
Popular Course in this category
Free Java Online Course
4+ Hours | Lifetime Access | Verifiable Certificates
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more