Java Stream Operations Tutorial 🎯

beginner
15 min

Java Stream Operations Tutorial 🎯

Welcome to this comprehensive guide on Java Stream Operations! We'll dive deep into understanding this powerful feature of Java that simplifies data processing. By the end of this tutorial, you'll be equipped with the knowledge to apply Java Stream Operations in your own projects.

What are Java Streams? 📝

In Java, Streams are sequences of elements that allow you to perform operations on a collection of data. Think of a stream as a pipeline where data flows through a series of methods.

Why use Streams?

  • Efficiency: Streams perform operations lazily, which means they only execute when a result is needed. This reduces memory usage and improves performance.
  • Functional Programming: Streams support functional-style operations, helping you write cleaner, more concise code.

Creating a Stream 🎯

To create a Stream, we use the stream() method on a collection. Let's create a Stream from a simple List<Integer>:

java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); Stream<Integer> numberStream = numbers.stream();

Basic Stream Operations 💡

1. Filtering

Filter out elements based on a condition.

java
// Filter even numbers Stream<Integer> evenNumbers = numberStream.filter(num -> num % 2 == 0);

2. Mapping

Transform each element to another form.

java
// Map numbers to their squares Stream<Integer> squaredNumbers = numberStream.map(num -> num * num);

3. Reducing

Combine all elements into a single value.

java
// Sum of all numbers int sum = numberStream.reduce(0, Integer::sum);

Intermediate Operations 💡

Intermediate operations create a new Stream, while terminal operations produce a result.

1. Collecting Results 📝

Collect the results into a collection, like a List or a Set.

java
List<Integer> squaredNumbersList = numberStream.map(num -> num * num).collect(Collectors.toList());

2. Counting Elements 💡

Count the number of elements in the Stream.

java
long numberCount = numberStream.count();

Advanced Stream Operations 💡

1. Parallel Streams 💡

Process elements concurrently to utilize multiple CPU cores.

java
Stream<Integer> numberStreamParallel = numbers.parallelStream();

2. Customizing Operations 💡

Use functional interfaces to customize operations for specific needs.

java
// Custom filter operation Predicate<Integer> evenPredicate = num -> num % 2 == 0; Stream<Integer> evenNumbersCustom = numberStream.filter(evenPredicate);
Quick Quiz
Question 1 of 1

Which method do we use to create a Stream in Java?

Quick Quiz
Question 1 of 1

What does a Stream do in Java?