Java Collections Java 8 Stream API

In Java 8, the `Stream` API was introduced as part of the Java Collections Framework to provide a powerful way of working with collections of data. The `Stream` API allows you to process data in a declarative way using functional-style operations. Here are some basics of the `Stream` API in Java:

1. Creating a `Stream`: To create a `Stream`, you can use the `stream` method of a collection. For example:

List names = Arrays.asList("Alice", "Bob", "Charlie");

Stream stream = names.stream();

Here, a `Stream` is created from a `List` of strings.

2. Intermediate operations: Intermediate operations are operations that transform a `Stream` into another `Stream`. Some examples of intermediate operations include `filter`, `map`, and `sorted`. For example:

Stream filteredStream = stream.filter(name -> name.startsWith("A"));
Stream lengthStream = filteredStream.map(String::length);
Stream sortedStream = lengthStream.sorted();

Here, a `Stream` is first filtered to include only names that start with “A”, then mapped to their lengths, and finally sorted in ascending order based on length.

3. Terminal operations: Terminal operations are operations that produce a result or a side-effect. Some examples of terminal operations include `forEach`, `reduce`, and `collect`. For example:

sortedStream.forEach(System.out::println);
int totalLength = lengthStream.reduce(0, Integer::sum);
List filteredNames = names.stream().filter(name -> name.length() > 4).collect(Collectors.toList());

Here, the sorted `Stream` is printed to the console, the total length of the original `Stream` is computed using `reduce`, and a new `List` of filtered names is created using `collect`.

4. Parallel streams: The `Stream` API also provides a way to process data in parallel using the `parallelStream` method. For example:

List names = Arrays.asList("Alice", "Bob", "Charlie");

int totalLength = names.parallelStream()
                      .filter(name -> name.length() > 4)
                      .mapToInt(String::length)
                      .sum();

Here, the `parallelStream` method is used to process the `List` of names in parallel, and the total length of names longer than four characters is computed using `sum`.

The `Stream` API in Java 8 is a powerful tool that allows you to process collections of data in a declarative way using functional-style operations. By understanding the basics of the `Stream` API, you can write more efficient and effective code that can handle complex data structures.