Sitemap

Java Streams

8 min readJan 7, 2024

--

We are extensively integrating Java Streams into our daily coding practices without delving into the internals workings of streams. Java Streams prove particularly beneficial for processing larger datasets but not extensive beneficial for smaller dataset . We aim to explore the nuances of Java Streams and it’s various operations.

What is Java Stream ?

A Stream in Java is a sequence of elements supporting sequential and parallel aggregate operations. Think of it as a conveyor belt in a factory where elements (data) move along, and various operations (like filtering, sorting, etc.) can be performed on them.

It’s important to understand that a stream doesn’t store data. It simply conveys data from a source (like a collection or an array) through a pipeline of computational steps.

Let’s clarify this with an example. Imagine you have a list of numbers ranging from 1 to 10000. Your task is to identify the even numbers or the numbers that are perfect squares.

Without Java Streams API

for (Integer value : list) {
if(value % 2 == 0) {
ans.add(value);
} else if(isPerfectSquare(value)) {
ans.add(value);
}
}

With Java Streams API

List<Integer> ans = list.stream()
.filter(value -> value % 2 == 0 || isPerfectSquare(value))
.collect(Collectors.toList());

Phases of Stream

Press enter or click to view image in full size

Creation: A stream is created from a source, which can be a collection, an array, a generator function, or an I/O channel. For example, you can create a stream from a list using list.stream().

Intermediate Operations: These operations are applied on the stream and return a new stream. They are lazy, meaning they don’t start processing the elements until a terminal operation is invoked. Common intermediate operations include filter (filters elements based on a predicate), map (transforms each element into another form), sorted (sorts the elements), and distinct (removes duplicates).

Terminal Operations: These operations produce a result or a side-effect. Once a terminal operation is performed, the stream can no longer be used. Common terminal operations include forEach (performs an action for each element), collect (transforms the stream into a different form, like a List or a Set), reduce (combines elements to produce a single summary result), and count (returns the number of elements).

Short-circuiting Operations: Some operations, like findFirst or anyMatch, do not need to process the entire stream to produce a result. They are called short-circuiting operations because they can terminate early.

Remember, streams are designed to be used just once. After a terminal operation has been performed, the stream pipeline is considered consumed, and no further operations can be performed on it.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {
public static void main(String[] args) {
List<String> myList = Arrays.asList("delhi", "udaipur", "dehradun", "jaipur");

List<String> filteredList = myList.stream() // Creation
.filter(s -> s.startsWith("d")) // Intermediate Operation
.map(String::toUpperCase) // Intermediate Operation
.collect(Collectors.toList()); // Terminal Operation

System.out.println(filteredList);
}
}

Stream Internal Architecture

LinkedList Structure:

  1. Java Streams use a LinkedList-like structure to store a chain of stream operations.
  2. Each node in this linked list represents an operation applied to the stream (like filter, map, sorted).
  3. The stream starts from a source (like a collection), and each subsequent operation is added as a new node in the list.

Bitmap Flags

  1. Each stage (or node) in the stream’s internal linked list is assigned a set of bitmap flags. These flags represent certain characteristics or optimizations applicable to that stage.
  2. The flags include SIZED, DISTINCT, SORTED, and ORDERED.
    These flags help the stream framework to optimize the execution plan and make decisions about how to best process the stream.

Meaning of Flags

  • SIZED: Indicates that the size of the stream is known. This is useful for optimization, especially when creating new collections from the stream.
  • DISTINCT: Implies that the elements in the stream are unique. This can be used to avoid unnecessary checks for duplicates.
  • SORTED: Means that the elements in the stream are sorted. This is important for operations that depend on the order, like limit or skip.
  • ORDERED: Indicates whether the stream has a meaningful encounter order. In ordered streams, the order in which elements are encountered should be preserved.

The above concepts are quite theoretical; let’s try to clarify them with some practical examples.

Set<String> cities = new HashSet<>(Arrays.asList("udaipur", "jaipur", "delhi", "hariyana", "dehrandun"));

List<String> stream = cities.stream()
.distinct() // This operation can be skipped
.map(String::toUpperCase)
.toList();

When we call .distinct() on the stream, the stream is able to recognize that the source is a Set and thus already contains distinct elements. The internal optimization flags (like the ones we discussed earlier) allow the stream to skip the distinct operation entirely, as it’s redundant.

Stream Execution

Lazy Execution:

  1. Java Streams are “lazily executed”. This means that they don’t actually perform any computation until a terminal operation (like collect, forEach, reduce) is invoked.
  2. The intermediate operations (like map, filter, flatMap) just define the pipeline and are only executed when the terminal operation triggers the processing.

Stateless vs. Stateful Operations:

Press enter or click to view image in full size
  1. Stateless Operations: These operations, such as filter, map, or flatMap, do not retain state from previously processed elements. They can process each element independently.
  2. Stateful Operations: In contrast, operations like sorted, limit, or distinct are stateful. They need information about other elements in the stream to produce a result. For example, sorted needs to see all elements to sort them.

The above concepts are quite theoretical; let’s try to clarify them with some practical examples.

Get Perul Jain’s stories in your inbox

Join Medium for free to get updates from this writer.

Example 1 :

List<String> cities = List.of("delhi", "udaipur", "jaipur", "dehradun");

List<String> filteredCities = cities.stream()
.filter(city -> {
System.out.println("filter : " + city);
return city.startsWith("d");
})
.map(city -> {
System.out.println("map : " + city);
return city.toUpperCase();
})
.toList();

From the code provided above, one might assume that the list is first filtered and then the map operation is applied. However, that is not necessarily how it works.

Since both filter and map operations are stateless, they process each element independently.

Now let see output of above code

Press enter or click to view image in full size

As observed, each element is processed independently, with the filter and map operations being applied to each element separately.

Example 2 :

List<String> cities = List.of("delhi", "udaipur", "jaipur", "dehradun");

List<String> filteredCities = cities.stream()
.filter(city -> {
System.out.println("filter : " + city);
return city.startsWith("d");
})
.distinct()
.map(city -> {
System.out.println("map : " + city);
return city.toUpperCase();
})
.toList();
  1. The filter and map operations process each element independently.
  2. The distinct operation does not process each element independently, as it relies on the state of previously processed elements to function correctly.

The combination of stateful and stateless operations in this stream means that while some elements (like those being filtered and mapped) are processed independently, the overall stream processing is not entirely independent due to the stateful nature of the distinct operation.

Example 3 :

List<String> cities = List.of("delhi", "udaipur", "jaipur", "dehradun");

List<String> filteredCities = cities.stream()
.filter(city -> {
System.out.println("filter : " + city);
return city.startsWith("d");
})
.map(city -> {
System.out.println("map : " + city);
return city.toUpperCase();
})
.sorted()
.toList();

Output

Press enter or click to view image in full size

In the example provided, both map and filter are stateless operations. Therefore, they are applied independently to each element. Subsequently, sorting is applied, which is a stateful operation.

Example 4 :

List<String> cities = List.of("delhi", "udaipur", "jaipur", "dehradun");

List<String> filteredCities = cities.stream()
.filter(city -> {
System.out.println("filter : " + city);
return city.startsWith("d");
})
.sorted()
.map(city -> {
System.out.println("map : " + city);
return city.toUpperCase();
})
.toList();

System.out.println("sorted list : " + filteredCities);

Output :

Press enter or click to view image in full size

The output above demonstrates that initially, all elements undergo a filtering process. Subsequently, the remaining elements are mapped and finally sorted.

  1. The main difference is the order of the map and sorted operations. In example 3 , cities are sorted in their original (lowercase) form and then converted to uppercase. In Example 4, cities are first converted to uppercase and then sorted
  2. This leads to a potential difference in the sorting order. Since sorting is case-sensitive, the uppercase conversion before sorting in Example 4 can lead to a different order compared to Example 3.

Parallel Streams

  • Parallel streams split the data into multiple chunks, processing them in parallel threads.
  • They utilize the Fork/Join framework in Java, which allows tasks to be split into smaller tasks and then combined (joined) to produce a result.

The above concepts are quite theoretical; let’s try to clarify them with some practical examples.

Example 1 :

List<String> cities = List.of("delhi", "udaipur", "jaipur", "dehradun");

List<String> filteredCities = cities.parallelStream()
.filter(city -> {
System.out.println("Thread : " + Thread.currentThread().getName() + " filter : " + city);
return city.startsWith("d");
})
.map(city -> {
System.out.println("Thread : " + Thread.currentThread().getName() + " map : " + city);
return city.toUpperCase();
})
.toList();

System.out.println("sorted list : " + filteredCities);

Output

Press enter or click to view image in full size

parallelStream() is called on the cities list. This creates a parallel stream, which means the stream operations can be executed in parallel across multiple threads.

In our example, it’s possible that:

  • The filter operation for a particular city (like "delhi") could be executed in one thread.
  • The subsequent map operation for the same city could be executed in a different thread.

This behavior is part of what makes parallel streams powerful, as it allows for the efficient utilization of multiple cores of the CPU, potentially speeding up the processing of large collections of data.

However, for small data sets or less complex operations, parallel processing might be slower due to the overhead of managing multiple threads.

Points to Consider Before Using Java Streams ?

  1. Performance Overhead: For small collections or simple operations, the overhead of creating a Stream might not justify its benefits compared to traditional loops.
  2. Debugging Difficulty: Debugging a chain of Stream operations can be more challenging compared to traditional imperative code structures.
  3. Readability Issues: While Streams can make code more concise, they can also make it less readable, especially for those not familiar with functional programming concepts.
  4. Memory Consumption: Intermediate operations in Streams can consume more memory, as they may need to maintain the state of the data being processed.

Conclusion

Java Streams provide an efficient and intuitive framework for processing collections of data. Their ability to perform complex operations through a combination of stateless and stateful methods, along with the flexibility of sequential and parallel processing, makes them an indispensable tool in a Java developer’s life. While they shine in handling large datasets, it’s important to use them judiciously, considering the overhead in smaller data sets or simpler tasks. Understanding their internal workings, particularly for optimization and execution, is key to leveraging their full potential for clean, efficient, and maintainable code.

--

--