Streams in Java 8 with Examples

Streams In Java 8, the Streams concept was introduced to process objects of collections efficiently. It provides a streamlined way to perform operations on collections such as filtering, mapping, and aggregating data.

Differences between java.util.streams and java.io streams

The java.util.streams are designed for processing objects from collections, representing a stream of objects. On the other hand, java.io streams are used for handling binary and character data in files, representing streams of binary or character data. Therefore, java.io streams and java.util streams serve different purposes.

Difference between Collection and Stream

A Collection is used to represent a group of individual objects as a single entity. On the other hand, a Stream is used to process a group of objects from a collection sequentially.

To convert a Collection into a Stream, you can use the stream() method introduced in Java 8:

Stream<T> stream = collection.stream();

Once you have a Stream, you can process its elements in two phases:

  1. Configuration: Configuring the Stream pipeline using operations like filtering and mapping.Filtering: Use the filter() method to filter elements based on a boolean condition:
Stream<T> filteredStream = stream.filter(element -> elementCondition);

Mapping: Use the map() method to transform elements into another form:

Stream<R> mappedStream = stream.map(element -> mapFunction);

2. Processing: Performing terminal operations to produce a result or side-effect.

  • Collecting: Use the collect() method to collect Stream elements into a Collection:
List<T> collectedList = stream.collect(Collectors.toList());

Counting: Use the count() method to count the number of elements in the Stream:

long count = stream.count();

Sorting: Use the sorted() method to sort elements in the Stream:

List<T> sortedList = stream.sorted().collect(Collectors.toList());

Min and Max: Use min() and max() methods to find the minimum and maximum values:

Optional<T> min = stream.min(comparator);
Optional<T> max = stream.max(comparator);

Iteration: Use the forEach() method to iterate over each element in the Stream:

stream.forEach(element -> System.out.println(element));

Array Conversion: Use the toArray() method to convert Stream elements into an array:

T[] array = stream.toArray(size -> new T[size]);

Stream Creation: Use the Stream.of() method to create a Stream from specific values or arrays:

Stream<Integer> intStream = Stream.of(1, 2, 3, 4, 5);

Java Stream API Example

These examples demonstrate the basic operations and benefits of using Streams in Java 8 for efficient data processing.

Example with Filtering and Mapping

Consider filtering even numbers from a list using Streams:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
                                   .filter(num -> num % 2 == 0)
                                   .collect(Collectors.toList());
System.out.println("Even numbers: " + evenNumbers);

Example with Mapping

Transforming strings to uppercase using Streams:

List<String> names = Arrays.asList("John", "Jane", "Doe", "Alice");
List<String> upperCaseNames = names.stream()
                                  .map(name -> name.toUpperCase())
                                  .collect(Collectors.toList());
System.out.println("Upper case names: " + upperCaseNames);

These examples illustrate how Streams facilitate concise and efficient data processing in Java 8.

Additional Examples

Example with collect() Method

Collecting only even numbers from a list without Streams:

import java.util.*;

public class Test {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i <= 10; i++) {
            list.add(i);
        }
        System.out.println("Original list: " + list);
        
        ArrayList<Integer> evenNumbers = new ArrayList<>();
        for (Integer num : list) {
            if (num % 2 == 0) {
                evenNumbers.add(num);
            }
        }
        System.out.println("Even numbers without Streams: " + evenNumbers);
    }
}

Collecting even numbers using Streams:

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

public class Test {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i <= 10; i++) {
            list.add(i);
        }
        System.out.println("Original list: " + list);
        
        List<Integer> evenNumbers = list.stream()
                                       .filter(num -> num % 2 == 0)
                                       .collect(Collectors.toList());
        System.out.println("Even numbers with Streams: " + evenNumbers);
    }
}

These updated examples showcase both traditional and streamlined approaches to handling collections in Java, emphasizing the efficiency and readability benefits of Java 8 Streams.

Streams in Java 8: Conclusion

The Java Stream API in Java 8 offers a powerful way to process collections with functional programming techniques. By simplifying complex operations like filtering and mapping, Streams enhance code clarity and efficiency. Embracing Streams empowers developers to write cleaner, more expressive Java code, making it a valuable tool for modern application development.

Click here

Leave a Comment