Java Stream API Introduction 🎯

beginner
7 min

Java Stream API Introduction 🎯

Welcome to our comprehensive guide on the Java Stream API! This tutorial is designed to help both beginners and intermediates understand the power of Java's Stream API in a practical and engaging way.

What is Java Stream API? 📝

Java Stream API is a functional programming tool that allows you to perform operations (like filtering, mapping, and reducing) on collections (like arrays, lists, and sets) in Java 8 and later versions. It provides a declarative way to process data, making your code more concise, efficient, and easier to read.

Why use Java Stream API? 💡

  • Improved Performance: Stream API uses parallel processing for better performance and efficiency, especially with large datasets.
  • Concise Code: Stream API allows you to write less code by chaining methods together.
  • Functional Programming: Stream API is a part of Java's support for functional programming, a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

Getting Started with Java Stream API 🎯

Importing Stream API

Before you can use Stream API, you need to import the java.util.stream package.

java
import static java.util.stream.Stream.*;

Basic Stream Operations

Let's create a simple list of integers and perform basic stream operations:

java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); // Filtering Stream<Integer> evenNumbers = numbers.stream().filter(n -> n % 2 == 0); evenNumbers.forEach(System.out::println); // Output: 2 4 // Mapping Stream<Integer> squaredNumbers = numbers.stream().map(n -> n * n); squaredNumbers.forEach(System.out::println); // Output: 1 4 9 16 25 // Reducing int sum = numbers.stream().reduce(0, Integer::sum); System.out.println("Sum: " + sum); // Output: 15

In this example, we created a list of integers, filtered out the even numbers, squared each number, summed all numbers, and printed the results.

Intermediate and Advanced Stream Operations 🎯

  • Distinct: Retains only the distinct elements in the stream.
  • Sorted: Sorts the elements in the stream.
  • Limit: Limits the number of elements to a specified number.
  • Skip: Skips the first n elements.
  • Collect: Groups the elements into a data structure like a list, set, or map.
java
// Distinct Stream<Integer> distinctNumbers = numbers.stream().distinct(); distinctNumbers.forEach(System.out::println); // Output: 1 2 3 4 5 // Sorted Stream<Integer> sortedNumbers = numbers.stream().sorted(); sortedNumbers.forEach(System.out::println); // Output: 1 2 3 4 5 // Limit and Skip Stream<Integer> skippedNumbers = numbers.stream().skip(2).limit(3); skippedNumbers.forEach(System.out::println); // Output: 3 4 5 // Collect to List List<Integer> list = numbers.stream().collect(Collectors.toList()); System.out.println(list); // Output: [1, 2, 3, 4, 5]

Parallel Streams 🎯

You can use parallel streams to process elements concurrently for better performance with large datasets:

java
// Parallel Stream Stream<Integer> parallelNumbers = numbers.parallelStream(); parallelNumbers.forEach(System.out::println); // Output: 1 2 3 4 5 (in random order)

Terminal Operations 🎯

Terminal operations are the final operations that return a result and consume the stream:

  • count: Returns the number of elements in the stream.
  • min: Returns the smallest element in the stream.
  • max: Returns the largest element in the stream.
  • anyMatch, allMatch, noneMatch: Check if any, all, or no elements match a given predicate.
java
// count long count = numbers.stream().count(); System.out.println("Count: " + count); // Output: 5 // min and max OptionalInt minNumber = numbers.stream().min(); OptionalInt maxNumber = numbers.stream().max(); System.out.println("Min: " + minNumber.getAsInt()); // Output: 1 System.out.println("Max: " + maxNumber.getAsInt()); // Output: 5 // anyMatch, allMatch, noneMatch boolean hasEvenNumber = numbers.stream().anyMatch(n -> n % 2 == 0); boolean areAllEven = numbers.stream().allMatch(n -> n % 2 == 0); boolean hasOddNumber = numbers.stream().noneMatch(n -> n % 2 == 0); System.out.println("Has Even Number: " + hasEvenNumber); // Output: true System.out.println("Are All Even: " + areAllEven); // Output: false System.out.println("Has Odd Number: " + hasOddNumber); // Output: true

Quiz 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the Java Stream API?

That's it for this comprehensive introduction to Java Stream API! By now, you should have a good understanding of what Stream API is, why we use it, and how to perform basic and intermediate operations. Happy coding! 🚀