A Collection is an in-memory data structure that stores elements. All elements must exist before being added and you can perform operations like search, sort, insert, update or delete. Examples: List, Set, Queue, ArrayList, LinkedList, HashSet, etc.
On the other hand, A Stream (introduced in Java 8) is used to process collections of objects. It represents a sequence of elements and allows you to chain methods to produce results without changing the original collection.
Example: Collections
import java.io.*;
import java.util.*;
class GfG {
public static void main(String[] args)
{
// Creating an instance of list
List<String> companyList = new ArrayList<>();
// Adding elements using add() method
companyList.add("Google");
companyList.add("Apple");
companyList.add("Microsoft");
// Now creating a comparator
Comparator<String> com = (String o1, String o2) -> o1.compareTo(o2);
// Sorting the list
Collections.sort(companyList, com);
// Iterating using for each loop
for (String name : companyList) {
System.out.println(name);
}
}
}
Output
Apple Google Microsoft
Example: Streams
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Creating an empty Arraylist
List<String> companyList = new ArrayList<>();
// Adding elements to above ArrayList
companyList.add("Google");
companyList.add("Apple");
companyList.add("Microsoft");
// Sorting the list using sorted() method and using for-each loop
companyList.stream().sorted().forEach(
System.out::println);
}
}
Output
Apple Google Microsoft
Difference Between Streams and Collections
| Streams | Collections |
|---|---|
| Do not store data, operate on source data (like Collections/Arrays). | Store and hold data in structures like List, Set or Map. |
| Use functional style (lambdas, method references). | Do not use functional interfaces directly. |
| Consumable once used, must be recreated to traverse again. | Reusable can be traversed multiple times. |
| Support sequential and parallel processing. | Mostly sequential, parallelism requires extra effort. |
| Belong to java.util.stream package. | Belong to java.util package (e.g., List, Set, Queue). |
| Not modifiable, cannot add or remove elements. | Modifiable, elements can be added or removed. |
| Internal iteration (handled by the Stream API). | External iteration (using loops/iterators). |