Home RoadMap Blog Contact us Learn

5.Core Java Concepts: Java Streams

Core Java Concepts: Java Streams

The Java Stream API is a powerful tool for processing sequences of elements from collections such as List, Set, or arrays. It helps in performing operations such as filtering, mapping, and reducing in a functional style.

1. Stream API for Processing Collections

The Stream API provides a modern approach to handling collections. You can create a stream from a collection or array, and then process it using a chain of operations.

import java.util.Arrays;
import java.util.List;

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
       .filter(n -> n % 2 == 0)
       .forEach(System.out::println);  // Output: 2, 4

2. Intermediate Operations

Intermediate operations are lazy and return a new stream, allowing you to chain multiple operations together. Common intermediate operations include filter, map, and sorted.

Filter

filter() is used to select elements that meet a certain condition.

numbers.stream()
       .filter(n -> n > 2)
       .forEach(System.out::println);  // Output: 3, 4, 5

Map

map() transforms each element in a stream, applying a function to each one.

numbers.stream()
       .map(n -> n * 2)
       .forEach(System.out::println);  // Output: 2, 4, 6, 8, 10

Sorted

sorted() sorts the elements in the stream.

numbers.stream()
       .sorted()
       .forEach(System.out::println);  // Output: 1, 2, 3, 4, 5

3. Terminal Operations

Terminal operations trigger the processing of the stream. Once a terminal operation is called, the stream is consumed and can no longer be used. Common terminal operations include forEach, collect, and reduce.

ForEach

forEach() iterates over each element in the stream.

numbers.stream()
       .forEach(System.out::println);  // Output: 1, 2, 3, 4, 5

Collect

collect() gathers the elements of a stream into a collection or another data structure.

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

List<Integer> evenNumbers = numbers.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());

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

Reduce

reduce() performs a reduction on the elements of the stream, combining them into a single result.

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

System.out.println(sum);  // Output: 15
Quick Exercise: Try using the Stream API to filter, map, and collect a list of numbers, or find the sum using the reduce() method.

Conclusion

The Stream API in Java is an excellent way to work with collections in a functional style, improving code readability and making it easier to perform complex data manipulations in a concise manner.

Java Streams

Recent Posts