Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Comparing Streams to Loops in Java
Next article icon

Comparing Streams to Loops in Java

Last Updated : 20 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

A stream is an ordered pipeline of aggregate operations(filter(), map(), forEach(), and collect()) that process a (conceptually unbounded) sequence of elements. A stream pipeline consists of a source, followed by zero or more intermediate operations; and a terminal operation. An aggregate operation performs a function. Ideally, a function's output in a stream depends only on its input arguments. A stream holds no non-transient stage. Every stream works essentially the same which is:

  • Starts with a source of data.
  • Processes the data through a pipeline of intermediate operations.
  • Finishes with a terminal operation.

By default, each aggregate operation in a stream runs its function sequentially, i.e., one after another in the caller's thread of control. Streams can be created from Collections, Lists, Sets, ints, longs, doubles, arrays, lines of a file. 

Stream operations are either intermediate or terminal. Intermediate operations such as filter, map, or sort return a stream, so we can chain multiple intermediate operations. Terminal operations such as forEach, collect, or reduce are either void or return a non-stream result. Streams bring functional programming in Java and are supported starting in Java 8. The Java 8 stream is an implementation of the PQSA1 Pipes and Filter pattern.

Example:

Java
// Java Program to Compare Streams to Loops   // Importing required libraries import java.io.IOException; import java.lang.String; import java.nio.file.*; import java.util.*; import java.util.Arrays; import java.util.List; import java.util.stream.*;  // Main class // JavaStreams class GFG {      // Main driver method     public static void main(String[] args)         throws IOException     {          // 1. Integer Stream         System.out.println("Integer Stream : ");         IntStream.range(1, 10).forEach(System.out::print);          // New line         System.out.println();          // 2. Integer Stream with skip         System.out.println("Integer Stream with skip : ");         IntStream.range(1, 10).skip(5).forEach(             x -> System.out.println(x));          // New line         System.out.println();          // 3. Integer Stream with sum         System.out.println("Integer Stream with sum : ");         System.out.println(IntStream.range(1, 5).sum());          // New line         System.out.println();          // 4. Stream.of, sorted and findFirst         System.out.println(             "Stream.of, sorted and findFirst : ");         Stream.of("Java ", "Scala ", "Ruby ")             .sorted()             .findFirst()             .ifPresent(System.out::println);          // New line         System.out.println();          // 5. Stream from Array, sort, filter and print         String[] names = { "AI",        "Matlab",                            "Scikit",    "TensorFlow",                            "OpenCV",    "DeepLearning",                            "NLP",       "NeuralNetworks",                            "Regression" };         System.out.println(             "Stream from Array, sort, filter and print : ");         Arrays             .stream(names) // same as Stream.of(names)             .filter(x -> x.startsWith("S"))             .sorted()             .forEach(System.out::println);          // New line         System.out.println();          // 6. average of squares of an int array         System.out.println(             "Average of squares of an int array : ");         Arrays.stream(new int[] { 2, 4, 6, 8, 10 })             .map(x -> x * x)             .average()             .ifPresent(System.out::println);          // New line         System.out.println();          // 7. Stream from List, filter and print          // Display message only         System.out.println(             "Stream from List, filter and print : ");          List<String> people = Arrays.asList(             "AI", "Matlab", "Scikit", "TensorFlow",             "OpenCV", "DeepLearning", "NLP",             "NeuralNetworks");         people.stream()             .map(String::toLowerCase)             .filter(x -> x.startsWith("a"))             .forEach(System.out::println);          // New line         System.out.println();          // 8. Reduction - sum          // Display message only         System.out.println("Reduction - sum : ");          double total             = Stream.of(7.3, 1.5, 4.8)                   .reduce(0.0,                           (Double a, Double b) -> a + b);          // Print and display         System.out.println("Total = " + total);          System.out.println();          // 9. Reduction - summary statistics         System.out.println(             "Reduction - summary statistics : ");         IntSummaryStatistics summary             = IntStream.of(7, 2, 19, 88, 73, 4, 10)                   .summaryStatistics();          // Print and display         System.out.println(summary);          System.out.println();     } } 

 
 


Output
Integer Stream :  123456789 Integer Stream with skip :  6 7 8 9  Integer Stream with sum :  10  Stream.of, sorted and findFirst :  Java   Stream from Array, sort, filter and print :  Scikit  Average of squares of an int array :  44.0  Stream from List, filter and print :  ai  Reduction - sum :  Total = 13.600000000000001  Reduction - summary statistics :  IntSummaryStatistics{count=7, sum=203, min=2, average=29.000000, max=88}


 

Now, discussing loops in order to figure out in order to land onto conclusive differences. Looping is a feature in Java that facilitates the execution of a set of instructions until the controlling Boolean expression evaluates to false. Different types of loops are provided to fit any programming need. Each loop has its own purpose and a suitable use case to serve.


 

Example:

Java
// Java Program to Comparing Streams to Loops  // Importing utility packages import java.util.*;  // Class 1 // helper class  class ProgrammingLanguage {      // Member variables of this class     int rank;     String name;     int value;      // Member method of this class     public ProgrammingLanguage(int rank, String name,                                int value)     {          // this keyword is used to refer current object         // itself         this.rank = rank;         this.name = name;         this.value = value;     } }  // Class 2 // JavaStreamExample public class GFG {      // MAin driver method     public static void main(String[] args)     {          // Creating an object of List class         // Declaring object of user defined type (above         // class)         List<ProgrammingLanguage> programmingLanguage             = new ArrayList<ProgrammingLanguage>();          // Adding elements to the object of this class         // Custom input entries         programmingLanguage.add(             new ProgrammingLanguage(1, "Java", 7000));         programmingLanguage.add(             new ProgrammingLanguage(2, "Rust", 2000));         programmingLanguage.add(             new ProgrammingLanguage(3, "Ruby", 1500));         programmingLanguage.add(             new ProgrammingLanguage(4, "Scala", 2500));         programmingLanguage.add(             new ProgrammingLanguage(5, "Groovy", 4000));          // Creating object of List class of integer type         List<Integer> languageValueList             = new ArrayList<Integer>();          // For each loops for iteration         for (ProgrammingLanguage language :              programmingLanguage) {              // Filtering data of List             if (language.value < 3000) {                  // Adding price to above elements                 languageValueList.add(language.value);             }         }          // Print and display all elements inside the object         System.out.println(languageValueList);     } } 

Output
[2000, 1500, 2500]

By far we have understood both of the concepts and come across to know they don't go hand in hand, one has advantage over other as per the usage where it is to be used. Hence, wrapping off the article by illustrating their advantages which are as follows:  

Advantages of Streams 

  • Streams are a more declarative style. Or a more expressive style.
  • Streams have a strong affinity with functions. Java 8 introduces lambdas and functional interfaces, which opens a whole toolbox of powerful techniques. Streams provide the most convenient and natural way to apply functions to sequences of objects.
  • Streams encourage less mutability. This is sort of related to the functional programming aspect i.e., the kind of programs we write using streams tend to be the kind of programs where we don't modify objects.
  • Streams encourage loose coupling. Our stream-handling code doesn't need to know the source of the stream or its eventual terminating method.
  • Streams can succinctly express quite sophisticated behavior.


 

Advantages of Loops 

  • Performance: A for loop through an array is extremely lightweight both in terms of heap and CPU usage. If raw speed and memory thriftiness is a priority, using a stream is worse.
  • Familiarity: The world is full of experienced procedural programmers, from many language backgrounds, for whom loops are familiar and streams are novel. In some environments, you want to write code that's familiar to that kind of person.
  • Cognitive overhead: Because of its declarative nature, and increased abstraction from what's happening underneath, you may need to build a new mental model of how code relates to execution. Actually, you only need to do this when things go wrong, or if you need to deeply analyze performance or subtle bugs. When it “just works”, it just works.
  • Debuggers are improving, but even now, when we are stepping through stream code in a debugger, it can be harder work than the equivalent loop, because a simple loop is very close to the variables and code locations that a traditional debugger works with.


 

Conclusion: 

If you have a small list; for loops perform better, if you have a huge list; a parallel stream will perform better. And since parallel streams have quite a bit of overhead, it is not advised to use these unless you are sure it is worth the overhead.


Next Article
Comparing Streams to Loops in Java

V

vanshitatwr620
Improve
Article Tags :
  • Java
  • Difference Between
  • java-stream
Practice Tags :
  • Java

Similar Reads

    Compare two Strings in Java
    String in Java are immutable sequences of characters. Comparing strings is the most common task in different scenarios such as input validation or searching algorithms. In this article, we will learn multiple ways to compare two strings in Java with simple examples.Example:To compare two strings in
    4 min read
    Short compare() method in Java
    The compare() method of Short class is used to compare two primitive short values for numerical equality. As it is a static method therefore it can be used without creating any object of Short. Syntax: public static int compare(short x, short y) Parameters: This method accepts two parameters: x: whi
    2 min read
    For Loop in Java | Important points
    Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. In Java, just unlikely any programming language provides four ways for executing the loops namely while loop, for loop, for-each loop, do
    6 min read
    YearMonth compareTo() method in Java
    The compareTo() method of YearMonth class in Java is used to compare two YearMonth objects. It compares this YearMonth object to the YearMonth object passed to it as parameter. The comparison between the two YearMonth instances is first done on the value of Year and then on the Month. Syntax: public
    2 min read
    For-Each Loop in Java
    The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required.Example: Using a for-each lo
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences