Java Stream

blog_4

Absolutely! Here’s a crash course on Java Streams — a powerful feature introduced in Java 8 that allows for functional-style operations on collections of data.


🔹 What is a Java Stream?

A Stream is not a data structure, but rather a sequence of elements from a source (like a collection) that supports aggregate operations.

Think of it like a pipeline for transforming data.


🔹 Stream Basics

To use streams, you usually follow 3 steps:

  1. Create a Stream
  2. Apply Intermediate Operations (like filter, map, etc.)
  3. Apply a Terminal Operation (like collect, forEach, etc.)

🔸 Example: Filtering and printing names

List<String> names = List.of("John", "Jane", "Jack", "Tom");

names.stream()
     .filter(name -> name.startsWith("J"))
     .forEach(System.out::println);
Java

Output:

John
Jane
Jack
Java

🔹 Stream Types

  • Sequential Stream: processes elements one by one
  • Parallel Stream: processes elements in parallel (multi-threaded) → use with caution
list.parallelStream()
Java

🔹 Common Stream Operations

🔸 filter()

Filters elements based on a condition

stream.filter(x -> x > 10)
Java

🔸 map()

Transforms each element

stream.map(String::toUpperCase)
Java

🔸 sorted()

Sorts the elements

stream.sorted()
Java

🔸 distinct()

Removes duplicates

stream.distinct()
Java

🔸 limit() / skip()

Limit or skip elements

stream.limit(3)
Java

🔹 Terminal Operations

🔸 collect()

Collects results into a collection

List<String> result = stream.collect(Collectors.toList());
Java

🔸 forEach()

Performs an action for each element

stream.forEach(System.out::println);
Java

🔸 count()

Counts elements

long count = stream.count();
Java

🔸 reduce()

Reduces elements to a single value

int sum = stream.reduce(0, Integer::sum);
Java

🔹 Example: Convert List of names to uppercase and collect them

List<string> names = List.of("john", "jane", "jack");<br><br>List<string> upperNames = names.stream()<br>                               .map(String::toUpperCase)<br>                               .collect(Collectors.toList());<br></string></string>
Java

🔹 Advanced: Grouping and Partitioning

Map<Boolean, List<Integer>> partitioned = numbers.stream()
    .collect(Collectors.partitioningBy(n -> n % 2 == 0));
Java

🔹 Stream vs Traditional Loop

Loop:

List<String> result = new ArrayList<>();
for (String name : names) {
    if (name.length() > 3) {
        result.add(name.toUpperCase());
    }
}
Java

Stream:

List<String> result = names.stream()
    .filter(name -> name.length() > 3)
    .map(String::toUpperCase)
    .collect(Collectors.toList());
Java

🔹 Notes

  • Streams are lazy: intermediate operations don’t execute until a terminal operation is called.
  • Streams cannot be reused: once consumed, they are gone.

✅ Summary

Operation TypeExamples
Intermediatefilter(), map(), sorted()
Terminalcollect(), forEach(), reduce()
Collector HelperstoList(), joining(), groupingBy()

If you want, I can turn this into a cheat sheet PDF or a practice task sheet. Would you like that?

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *