$show=/label

A Guide to Streams in Java 8: In-Depth Tutorial With Examples

SHARE:

A quick guide to Java 8 Stream API with Examples. What are the areas are improved in Java 8 as compared to prior java versions(ex. Multicore CPU).

1. Stream API Overview

In this tutorial, We'll take a look at an in-depth tutorial with examples on Java 8 Stream API.

Java 8 introduced a new API which is called as Stream. This API supports processing the large data sets in a sequential and parallel model.
When we see the code that looks to the SQL query database.

Before that, you can take a look at the Java 8 Lambda Expression Rules to write the errorless code.

Java 8 Stream API Introduction


we'll learn about java 8 in the aspect of the following.


  • Impact of Multi-Core CPU
  • Anonymous Inner classes
  • Stream Pipe Line
  • Functional Interfaces
  • How java 8 code looks with Examples
Stream API provides a package java.util.stream. This API provides several methods to iterate over a stream. This iterator can be called as New Fancy Iterator.
These methods can be used as a chain of the pipeline with complex logic similar to the UNIX pipeline command as below.

grep 'Exception' application.log | grep -V 'Server Exception' | tail -10

2. Multicore CPU

By using stream API, we can express our logic at a high level and the execution part is taken care of by Stream Library. As part of this, developers need to worry about synchronizing. The synchronized keyword makes to put many efforts to handle the errors caused by multiple threads. This stream API avoids high error-prone and uses multi-core CPU effectively.

If we do not use much multi-threading then we will not be using all the cores in the CPU.  That means not utilizing all core properly. So, We will experience performance issues If we don't use all the core properly. Java 8 has been developed after considering all these issues.

Java 8 stream API consumes all available core effectively and improves the performance significantly. 

3. Anonymous Inner class

Prior to Java 8, Anonymous inner classes are widely used by all the developers.

Inerface AddOn {
 boolean addAddon(String addOnType);
}

public void processingCreditCardAddOn(int cardNumber, AddOn addOn){

 boolean isValid = ValidateAccountNumber(cardNumber);
 if(isValid){
  addOn.addAddon("Extra Reward Points")
 }
}

When we call the processingCreditCardAddOn() method from service class, the implementation for the AddOn interface. Instead of creating a new class with implementation, We can pass the anonymous class to this method as below.

processor.processingCreditCardAddOn(1234567898765432, new AddOn() {
 public boolean addAddon(String addOnType){
  
  //logic to add the addOnType to the given account number.
 }
})

Now the code has become non readable and looks ugly by seeing anonymous class implementation.
The same can be simplified and making it more readable using Lambda concept.

processingCreditCardAddOn(1234567898765432, (addOnType) ->  //logic to add the addOnType to the given account number );

4. Stream Pipe Line


Java Stream API is developed mainly for Big Data application to process the large data sets effectively using all the hardware.

Example on Stream API to find the error in the log file.

First converting the log content into stream.

Stream stream = Stream.of(responseContent.split("\n"));

String firstException = stream.filter(line -> line.indexOf("ERROR") > -1 || line.indexOf("Exception) > -1).findFirst();


Here, First a pipe line will be created and every operation that perform on stream are placed in this pipe line. In other words, After that what ever we do like filter(), map() etc all the operations are placed into pipe line. But all not executed immediately unless invoke terminal methods.

Terminal methods that close the stream by producing the result. Terminal methods examples are reduce(), count(), findFirst() etc.

Once any terminal method is invoked than code is optimized by API and executes in the best order.

5. Functional Interfaces


To work with streams, we must have an idea about functional interface.
If any interface has only one abstract method then it is called Functional Interfaces. Functional Interfaces can have any number of default and private methods.

Filter(), Map()
methods will be using internally Functional Interfaces.

Examples are BiConsumer, Predicate, BinaryOperator, Function. All these are in java.util.function package.


Find list of all Functional Interfaces introduced in Java 8.

6. Stream API Intermediate Operations


Every stream code or pipeline must-have a map() or filter() methods. These methods are called as Intermediate Functions because these methods again create a temporary Stream to hold the intermediate output.

Learn about all intermediate stream operations in-depth.

filter()
map()
flatMap()
distinct()
sorted()
peek()
limit()
skip()


7. Stream API Terminal Operations


After calling the intermediate methods, to collect the final output stream api has another set of methods. Those are called Terminal Operations. These methods produce output such as Collection, List, Set, or Optional values.

I have shown an in-depth tutorial on Terminal Operations.

toArray()
collect()
count()
reduce()
forEach()
forEachOrdered()
min()
max()
anyMatch()
allMatch()
noneMatch()
findAny()
findFirst()

8. Java 8 Examples


9. Conclusion


In this tutorial, We've seen an introduction to the new java 8 Stream API.

Next, the Seen impact of Multi-core CPU usage as compared to utilizing only single core without threading in the collection API.

Furthermore discussed Anonymous Inner classes and how lambda is replaced it.

Finally, Seen how the stream pipeline works and Functional Interfaces.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: A Guide to Streams in Java 8: In-Depth Tutorial With Examples
A Guide to Streams in Java 8: In-Depth Tutorial With Examples
A quick guide to Java 8 Stream API with Examples. What are the areas are improved in Java 8 as compared to prior java versions(ex. Multicore CPU).
https://1.bp.blogspot.com/-ZGBzihm59HM/XQiETuv0j-I/AAAAAAAABrE/tesKBVuDY2Iy-9PVc0a2lS-NCJl8TAj7wCLcBGAs/s320/Java%2B8%2BStream%2BAPI%2BIntroduction.PNG
https://1.bp.blogspot.com/-ZGBzihm59HM/XQiETuv0j-I/AAAAAAAABrE/tesKBVuDY2Iy-9PVc0a2lS-NCJl8TAj7wCLcBGAs/s72-c/Java%2B8%2BStream%2BAPI%2BIntroduction.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/06/java-8-stream-api.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/06/java-8-stream-api.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content