Java 8 Features Stream API

The Stream API is a feature introduced in Java 8 to provide a functional programming approach for processing collections of data. The Stream API allows us to perform various operations on a collection of data, such as filtering, mapping, and reducing, in a concise and efficient manner. Here are some basics of the Stream API in Java:

1. Creating a Stream: To create a stream in Java, you can call the `stream()` or `parallelStream()` method on a collection, such as a list or set. For example:

List numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream stream = numbers.stream();

Here, a stream is created from the list of numbers using the `stream()` method.

2. Intermediate Operations: Intermediate operations are operations that can be performed on a stream to modify or filter its elements. Some common intermediate operations include `filter()`, `map()`, and `sorted()`. For example:

List names = Arrays.asList("Alice", "Bob", "Charlie", "Dave", "Eve");
Stream stream = names.stream()
    .filter(name -> name.startsWith("A"))
    .map(String::toUpperCase)
    .sorted();

Here, an intermediate operation chain is used to filter names starting with “A”, map them to upper case, and sort them in alphabetical order.

3. Terminal Operations: Terminal operations are operations that can be performed on a stream to produce a result or side effect. Some common terminal operations include `forEach()`, `count()`, and `reduce()`. For example:

List numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
  .filter(n -> n % 2 == 0)
  .mapToInt(Integer::intValue)
  .sum();

System.out.println("Sum of even numbers: " + sum);

Here, a terminal operation chain is used to filter out the even numbers, map them to their integer values, and then sum them using the `sum()` method.

4. Parallel Streams: The Stream API also provides the ability to process elements in parallel by using the `parallelStream()` method instead of `stream()`. Parallel streams allow the processing of elements to be distributed across multiple threads, potentially improving performance. For example:

List numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.parallelStream()
  .filter(n -> n % 2 == 0)
  .mapToInt(Integer::intValue)
  .sum();

System.out.println("Sum of even numbers: " + sum);

Here, a parallel stream is used to perform the same operation as the previous example, but with potential performance improvements.

The Stream API is a powerful feature in Java 8 that can simplify and optimize the processing of collections of data. By understanding the basics of the Stream API and its various operations, you can write more efficient and effective code that can manipulate and process data in your applications.