Java Streams
SECTION 1: STREAM CONCEPTS
1. What is a Stream in Java?
A Stream in Java is a sequence of elements that supports functional-style operations. It was
introduced in Java 8.
A Stream is NOT a data structure. It does not store data. Instead, it processes data from a
source such as a Collection, Array, or I/O channel.
Streams allow operations like iltering, mapping, sorting, and reducing in a clean and
readable way.
List<Integer> numbers = [Link](1,2,3,4,5);
[Link]()
.filter(n -> n % 2 == 0)
.forEach([Link]::println);
In this example, stream() creates a stream, ilter() is an intermediate operation, and
forEach() is a terminal operation.
2. Di erence Between Collec on and Stream
Collection stores data in memory. Stream processes data.
Collection can be traversed multiple times. Stream can be consumed only once.
Collection operations are eager. Stream operations are lazy (until terminal operation is
called).
3. What is Stream Lifecycle?
Stream lifecycle consists of:
1. Source – Collection, array, or I/O.
2. Intermediate Operations – ilter(), map(), sorted(), etc.
3. Terminal Operation – collect(), forEach(), reduce(), etc.
Without a terminal operation, the stream pipeline does not execute.
4. What is Lazy Evalua on?
Intermediate operations in Stream are lazy. They are executed only when a terminal
operation is invoked.
List<String> list = [Link]("A","B","C");
[Link]()
ff
ti
f
f
ti
f
.filter(s -> {
[Link]("Filtering " + s);
return true;
}); // No output because no terminal operation
No output is printed because terminal operation is missing.
5. map() vs atMap()
map() transforms each element individually.
latMap() is used when each element produces multiple elements (like List of Lists).
List<List<String>> nested = [Link](
[Link]("A","B"),
[Link]("C","D")
);
[Link]()
.flatMap(List::stream)
.forEach([Link]::println);
latMap lattens nested collections into a single stream.
SECTION 2: PRACTICAL STREAM PROGRAMS
Employee Class Used in Examples
class Employee {
private String name;
private String department;
private double salary;
public Employee(String name, String department, double
salary) {
[Link] = name;
[Link] = department;
[Link] = salary;
}
public String getName() { return name; }
public String getDepartment() { return department; }
public double getSalary() { return salary; }
}
1. Count Occurrence of Each Element
List<String> list =
[Link]("A","B","A","C","B","A","D","B");
f
f
f
fl
Map<String, Long> frequency = [Link]()
.collect([Link](
s -> s,
[Link]()
));
[Link](frequency);
groupingBy groups elements and counting() counts occurrences.
2. Find Second Most Repeated Element (Basic Version)
String secondMost = [Link]()
.collect([Link](s -> s,
[Link]()))
.entrySet()
.stream()
.sorted([Link].<String,
Long>comparingByValue().reversed())
.skip(1)
.map([Link]::getKey)
.findFirst()
.orElse(null);
[Link](secondMost);
First we group and count. Then we sort by frequency in descending order, skip the irst, and
pick the second.
3. Find Duplicate Elements
Set<String> duplicates = [Link]()
.collect([Link](s -> s,
[Link]()))
.entrySet()
.stream()
.filter(e -> [Link]() > 1)
.map([Link]::getKey)
.collect([Link]());
[Link](duplicates);
4. Group Employees by Department
List<Employee> employees = [Link](
new Employee("John","IT",60000),
new Employee("Alice","HR",50000),
new Employee("Bob","IT",70000)
);
f
Map<String, List<Employee>> grouped = [Link]()
.collect([Link](Employee::getDepartment));
[Link](grouped);
5. Find Highest Salary Employee
Employee highest = [Link]()
.max([Link](Employee::getSalary))
.orElse(null);
[Link]([Link]());
6. Par on Even and Odd Numbers
List<Integer> numbers = [Link](1,2,3,4,5,6);
Map<Boolean, List<Integer>> partitioned = [Link]()
.collect([Link](n -> n % 2 == 0));
[Link](partitioned);
partitioningBy divides elements into two groups based on condition (true/false).
SECTION 3: PRODUCT EDGE CONCEPTS
Why Stream Cannot Be Reused?
Once a terminal operation is executed, the stream is closed. Reusing it throws
IllegalStateException.
Stream<String> stream = [Link]();
[Link]([Link]::println);
[Link]([Link]::println); // Error
Why Parallel Stream Can Be Risky?
Parallel streams use multiple threads.
If operations are not stateless or thread-safe, it may cause incorrect results.
Parallel stream should be used only when operations are independent and large data set
exists.
ti
ti