Stream API in Java : Java 8 features

Introduction to Java Stream API

stream api in java

The Stream API in Java is basically designed to process collections of data in a functional style, Stream API allows us to perform the operations like filtering, mapping, and reducing without modifying the original data structures.

  • Collections in Java are used to store data, and this data can include primitive values wrapped in their respective classes, such as integers, double or strings
  • The Java Stream API was introduced in Java 1.8 and is considered a significant feature that simplifies coding by reducing boilerplate or repeating codes.
  • Using the Stream API can significantly reduce the length of code, allowing developers to write complex operations in just a few lines.

Data Processing with Stream API

  • Stream API allows us to perform operations on sets of data or collections, such as changing values, filtering, and reducing.
  • The API creates a stream of values from a collection and it enables various operations which we can perform on a set of data.
  • Streams can be created from collections using the stream() method, which returns a stream interface that provides multiple methods for data manipulation

The Stream API allows us as a developers to:

  • Transform values: Modify the value in the new form
  • Filter data: We can filter the data based on some conditions
  • Aggregate data: Combine data or values

Stream Creation

Streams can be created from collections using the stream() method. This method returns a Stream interface, which provides multiple methods for data manipulation.

Example:


import java.util.*;
import java.util.stream.*;

public class StreamExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Creating a stream from a collection
        Stream<Integer> numberStream = numbers.stream();
        
        // Example: Filtering even numbers
        List<Integer> evenNumbers = numberStream
            .filter(n -> n % 2 == 0)
            .collect(Collectors.toList());

        System.out.println(evenNumbers); // Output: [2, 4]
    }
}

Features of Stream API

The Stream API is designed to work with collections and allows for bulk operations on data.

  • filter : Filters data based on a condition.
  • map : Transforms data.
  • collect : Collects results into a desired format (e.g., list, set).
  • reduce : combines all the elements in a collection (like an array or list) into one single value. 

Key methods include filter, map, and collect, which are essential for processing data streams effectively. It provides methods for filtering, mapping, and collecting data, which enhances performance and readability.

Example: Filtering and Mapping


List<String> names = Arrays.asList("John", "Jane", "Jack");

List<String> upperCaseNames = names.stream()
    .filter(name -> name.startsWith("J"))
    .map(String::toUpperCase)
    .collect(Collectors.toList());

System.out.println(upperCaseNames); // Output: [JOHN, JANE, JACK]

Characteristics of Streams

  • Once a stream is consumed (for example, an operation is performed), it cannot be reused.
  • Streams are designed to work with immutable data, that means the original collection remains unchanged during processing.
  • The Stream API supports parallel processing, allowing operations to be executed using multiple threads without manual thread management.

Example: Parallel Stream


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

int sum = numbers.parallelStream()
    .mapToInt(Integer::intValue)
    .sum();

System.out.println(sum); // Output: 15

Common Stream Operations

1. map : The map function takes each element in a collection (like an array or list) and changes it in some way based on a given rule. It’s like transforming every item into something new, one by one.

Example: Doubling numbers


List<Integer> numbers = Arrays.asList(1, 2, 3);

List<Integer> doubled = numbers.stream()
    .map(n -> n * 2)
    .collect(Collectors.toList());

System.out.println(doubled); // Output: [2, 4, 6]

2. filter : The filter function goes through a collection (like an array or list) and picks out only the elements that meet a specific condition. It’s like sorting out the items you want to keep based on certain rules, and leaving the rest behind.

Example: Filtering odd numbers


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> oddNumbers = numbers.stream()
    .filter(n -> n % 2 != 0)
    .collect(Collectors.toList());

System.out.println(oddNumbers); // Output: [1, 3, 5]

3. collect : The collect function gathers the elements from a collection and puts them into a new container, like a list, set, or map. It’s like collecting all the transformed or filtered items and organizing them into a new place.

Example: Using collect to gather even numbers into a list


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

// Collect even numbers into a new list
List<Integer> evenNumbers = numbers.stream()
                                           .filter(n -> n % 2 == 0)  // Filter even numbers
                                           .collect(Collectors.toList());  // Collect into a list

// Print the result
System.out.println("Even numbers: " + evenNumbers);

4. reduce : The reduce function combines all the elements in a collection (like an array or list) into one single value. It works by repeatedly applying a function to two elements at a time, combining them, and then using that result with the next element, until only one value remains. It’s like folding all the items into one result

Example: Summing numbers


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
                 .reduce(0, Integer::sum);

System.out.println(sum); // Output: 15

Conclusion

The Stream API, introduced in Java 8, enhances the way developers can process collections of data, providing a more functional approach to data manipulations. It is a powerful tool that enhances code efficiency and readability, making it easier for developers to handle data collections. It is important to understand the characteristics of streams, such as their one-time use and immutability, to effectively utilize them in Java applications

Mastering the Stream API can significantly improve a developer’s ability to write clean and efficient Java code

Explore our more articles

What is Stream API in Java with practical examples

The Stream API in Java is basically designed to process collections of data in a functional style, Stream API allows us to perform the operations like filtering, mapping, and reducing without modifying the original data structures.

The Java Stream API was introduced in Java 1.8 and is considered a significant feature that simplifies coding by reducing boilerplate or repeating codes. Using the Stream API can significantly reduce the length of code, allowing developers to write complex operations in just a few lines.

Features of Stream API in Java

The Stream API allows us as a developers to:
Transform values: Modify the value in the new form
Filter data: We can filter the data based on some conditions
Aggregate data: Combine data or values

What are the Features of Stream API in Java

The Stream API is designed to work with collections and allows for bulk operations on data.
filter : Filters data based on a condition.
map : Transforms data.
collect : Collects results into a desired format (e.g., list, set).
reduce : combines all the elements in a collection (like an array or list) into one single value. 
Key methods include filter, map, and collect, which are essential for processing data streams effectively. It provides methods for filtering, mapping, and collecting data, which enhances performance and readability.

Leave a Comment