In Java, both collections and streams are used to work with collections of data, but they serve different purposes and have distinct characteristics.
- Collection:-
- A collection in Java is a group of objects that are stored and manipulated as a single unit.
- Collections are typically used to store and manage data in data structures such as lists, sets, and maps.
- Common examples of collection classes in Java include ArrayList, HashSet, and HashMap.
- Collections allow us to add, remove, and manipulate elements directly in memory.
- They are well-suited for scenarios where we need to store and access data quickly and efficiently.
- Stream:-
- A stream in Java is a sequence of elements that we can process in a functional, declarative style.
- Streams are part of the Java Streams API, introduced in Java 8, and they provide a way to perform operations on collections in a more concise and expressive manner.
- Streams do not store data themselves; instead, they operate on data from a source, which can be a collection, an array, or an I/O channel.
- Stream operations can be divided into two categories: intermediate and terminal operations. Intermediate operations transform the data and return a new stream, while terminal operations produce a result or a side effect and close the stream.
- Streams promote a more functional and declarative programming style, making it easier to perform complex data manipulation operations like filtering, mapping, and reducing.
When to use Collections:
- Use collections when we need to store and manage a fixed set of data that you want to modify directly.
- Collections are suitable when we need to perform frequent add, remove, and update operations on your data.
When to use Streams:
- Use streams when we want to perform data processing and transformation operations on a collection in a functional, declarative way.
- Streams are particularly useful when we need to filter, map, aggregate, or transform data from a source collection.
- They are well-suited for scenarios where we want to express complex operations in a more concise and readable manner.
- Let’s see the difference between Collection and stream.
Here are five key differences between collections and streams in tabular format:
Aspect | Collections | Streams |
---|---|---|
Data Storage | Collections store data directly in memory, occupying space. | Streams do not store data; they operate on data from a source, which may be a collection or another data source. |
Mutability | Collections are mutable; you can add, remove, and modify elements in-place. | Streams are immutable; they do not modify the source data. Instead, they create a new stream with transformed data. |
Processing Style | Collections use an imperative programming style, often requiring explicit loops for data manipulation. | Streams promote a more functional and declarative programming style, enabling operations like filtering, mapping, and reducing in a concise manner. |
Eager vs. Lazy | Collections are eager; they perform operations immediately when called (e.g., adding, removing, iterating). | Streams are lazy; they perform operations only when a terminal operation is invoked, allowing for more efficient processing of large data sets. |
Statelessness | Collections inherently have state, and the order of elements matters in some cases (e.g., List). | Streams are stateless; they don’t maintain any state, making them suitable for parallel processing and functional transformations. |
These differences highlight the contrasting nature of collections and streams in terms of data storage, mutability, processing style, evaluation strategy (eager vs. lazy), and statelessness. Streams provide a more modern and functional approach to data processing, while collections are more traditional and focused on data storage and manipulation.
Here are examples for both collections and streams in Java, along with their uses and the expected outputs.
Collections Example:
import java.util.ArrayList;
import java.util.List;
public class CollectionsExample {
public static void main(String[] args) {
// Creating a list to store integers
List<Integer> numbers = new ArrayList<>();
// Adding elements to the list
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
// Iterating through the list and printing each element
System.out.println("Using Collections:");
for (int num : numbers) {
System.out.println(num);
}
}
}
Output:
Using Collections:
1
2
3
4
5
In this example, we use the ArrayList collection to store and manage a list of integers. We add elements to the list and then iterate through it using a for-each loop to print each element.
Streams Example:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamsExample {
public static void main(String[] args) {
// Creating a list of integers
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
// Using a stream to filter and double each element
List<Integer> doubledNumbers = numbers.stream()
.filter(num -> num % 2 == 0) // Filter even numbers
.map(num -> num * 2) // Double each number
.collect(Collectors.toList()); // Collect the results into a new list
// Printing the doubled numbers
System.out.println("Using Streams:");
doubledNumbers.forEach(System.out::println);
}
}
Output:
Using Streams:
4
8
In this example, we use a stream to perform a series of operations on a list of integers. We filter the even numbers, double each element using map
, and then collect the results into a new list. Finally, we print the doubled numbers. Streams allow us to express these operations in a more concise and declarative manner.
In summary, collections are for storing and managing data, while streams are for processing and transforming data in a functional and expressive way. Your choice between them depends on your specific use case and programming style preferences. Additionally, in many cases, you can use both collections and streams together to achieve your desired results efficiently.
That’s all about Java 8 Collection vs Stream.
See stream docs.
Other Java 8 tutorials.
- Difference between Anonymous Inner Class and Lambda Expression
- Java 8 Comparator comparing() example
- Java 8 Lambda Expressions Examples
- Write a program to find the nth Highest Salary using Java…
- Java 8 Functional Interface Examples
- Java 8 Supplier Examples
- Java 8 Consumer Examples
- Java 8 Predicate examples
- Java 8 default methods examples
- Java 8 static methods examples