For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 10 AM to 7 PM
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
Streams in Java were introduced in Java 8 to simplify data processing. A stream represents a sequence of objects that can be processed in a functional style. Unlike collections, streams do not store data but provide methods to perform operations such as filtering, mapping, and reducing. This allows developers to work with large datasets more efficiently and with cleaner code.
This tutorial on Streams in Java covers the key concepts, operations, and methods of the Stream API. You will learn about intermediate and terminal operations, features of streams, and practical examples with code snippets. The blog is designed to help learners understand how to use Java Streams effectively for building robust and maintainable applications.
Advance your Java programming expertise with our Software Engineering courses and elevate your learning to the next level.
Streams in Java are a feature introduced in Java 8 that allow developers to process collections of data in a functional and declarative manner. A stream represents a sequence of elements that can be transformed, filtered, or reduced using various operations.
Accelerate your tech career by mastering future-ready skills in Cloud, DevOps, AI, and Full Stack Development. Gain hands-on experience, learn from industry leaders, and develop the expertise that top employers demand.
Unlike collections, streams do not store data; they work on data sources such as lists, arrays, or I/O channels. Streams in Java support method chaining, lazy evaluation, and parallel processing, making them powerful for handling large datasets efficiently while keeping code clean, concise, and easy to maintain.
Intermediate operations are operations that change one stream into another stream. These operations are called "intermediate" because they do not produce a final result or a terminal operation but instead return a new stream that can be further operated upon. The following are a few common intermediate operations in Java Streams:
Must Read: Top 13 String Functions in Java
Terminal operations in Java streams are those operations that initiate the processing of the stream elements and return a non-stream result. Here are explanations for three common terminal operations:
Here is a program to demonstrate the use of Stream with the stream() method:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum: " + sum);
}
}
In this program, we have a list of integers called numbers that contains the values 1, 2, 3, 4, and 5.
We use the Stream API to create a stream from the numbers list by calling the stream() method. Then, we use the mapToInt() method to convert the stream of Integer objects to an IntStream, which allows us to perform numeric operations. Finally, we call the sum() method on the IntStream to calculate the sum of the numbers in the stream and then print it.
Java Streams provide several features that make it easy to process data collections concisely and efficiently. Here are some of the main features that streams provide:
Parallelism: Streams can be easily parallelized. This means that they can be split into multiple parts. Then, they are processed in parallel across multiple threads or processors. This can enhance performance for large datasets to a great extent.
Lazy Evaluation: As already mentioned, streams use lazy evaluation. This means intermediate operations are not executed until a terminal operation is called on the stream. This allows for more efficient use of resources and can improve performance for complex stream pipelines.
Method Chaining: Streams support method chaining. This allows multiple operations to be chained together into a single stream pipeline. This makes writing concise and readable codes that perform complex data transformations easy.
Non-mutating Operations: Streams provide a set of non-mutating operations that do not modify the original collection. However, these operations return a new stream with the desired changes instead. This can make it easier to reason about the code. It may also avoid unexpected side effects.
Functional Programming: Streams use functional programming concepts, such as higher-order functions and lambda expressions. It makes it easy to write expressive and reusable code.
Support for Different Data Sources: Streams can be created from various data sources, such as collections, arrays, or files. They can be easily converted into other data structures or formats.
Also Read: A Complete Guide to Java Keywords
The Java Stream interface provides several methods that allow you to perform various operations on a stream. Here are some of the Java stream interface methods:
Must Read: How to Use the Final Keyword in Java for Variables, Methods, and Classes
Now, let us look at an example of filtering a collection in Java using the Stream API:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// Create a list of strings
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("David");
names.add("Eve");
// Filter the list to get names starting with "A"
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
// Print the filtered list
for (String name : filteredNames) {
System.out.println(name);
}
}
}
Here is an example of iterating over a Stream in Java:
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// Create a Stream of integers from 1 to 5
Stream<Integer> stream = Stream.iterate(1, n -> n + 1)
.limit(5);
// Iterate over the Stream and print the elements
stream.forEach(System.out::println);
}
}
In this example, we create a Stream of integers using the Stream.iterate() method. The iterate() method takes an initial value (1 in this case) and a lambda expression that defines the function to generate the next value based on the previous value (n -> n + 1 in this case). We limit the stream to contain only 5 elements using the limit() method.
Here is an example of using the reduce() method with Stream in Java on a collection:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Create a list of integers
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Use reduce() to calculate the sum of the numbers
int sum = numbers.stream()
.reduce(0, Integer::sum);
System.out.println("Sum: " + sum);
}
}
Now, here is an example of using the Collectors method with Stream in Java for also calculating the sum of 1, 2, 3, 4, and 5:
Here's an example of using Stream in Java to find the maximum and minimum product prices from a collection:
Here is an example of using the count() method with Stream in Java to count the number of elements in a collection:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Create a list of strings
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");
// Use count() to get the number of elements
long count = names.stream().count();
System.out.println("Count: " + count);
}
}
Here is an example of using Stream in Java to convert a list into a set:
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// Create a list of integers
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(3); // Duplicate element
// Convert the list to a set using Collectors.toSet()
Set<Integer> uniqueNumbers = numbers.stream()
.collect(Collectors.toSet());
// Print the unique numbers in the set
for (Integer number : uniqueNumbers) {
System.out.println(number);
}
}
}
Now, here is an example of using Stream in Java to convert a list into a map:
Streams in Java simplify the way developers handle data by enabling functional-style operations on collections. They provide efficient tools for filtering, mapping, reducing, and transforming data without modifying the original source. With features like lazy evaluation, method chaining, and parallel execution, Streams in Java make code more readable and performance-driven.
This tutorial explained their core concepts, operations, and examples to help you understand practical applications. Mastering the Stream API equips developers to build scalable, clean, and efficient Java programs, making it an essential concept for anyone learning or working with modern Java development.
A collection is a data structure that stores and manages a group of objects. In contrast, a stream is a way to process a group of objects functionally and declaratively.
No, Java Streams are not thread-safe by default. If a stream is used by multiple threads concurrently, it can lead to race conditions and other concurrency issues.
Yes, Java Streams can be created with an infinite number of elements. This is done without loading all the data into memory at once, allowing for efficient processing of large datasets.
-9cd0a42cab014b9e8d6d4c4ba3f27ab1.webp&w=3840&q=75)
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
FREE COURSES
Start Learning For Free

Author|907 articles published