Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Java 8 FAQ: Top Questions

12. How can you chain multiple Stream operations in Java 8?

In Java 8, streams support method chaining, allowing multiple intermediate and terminal operations to be connected in a pipeline. This promotes a functional and readable approach to data processing.

πŸ—ΊοΈ Step-by-Step Instructions:

  1. Use stream() to create a stream from a collection.
  2. Apply intermediate operations like filter(), map(), sorted().
  3. End with a terminal operation like collect() or forEach().
  4. Each intermediate operation returns a new stream, enabling further chaining.

πŸ“₯ Example Input:

List names = Arrays.asList("John", "Jane", "Jack", "Tom", "Jill");

List result = names.stream()
                           .filter(n -> n.startsWith("J"))
                           .map(String::toUpperCase)
                           .sorted()
                           .collect(Collectors.toList());

πŸ† Expected Output:

[JACK, JANE, JILL, JOHN]

βœ… Java 8 Solution:

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

public class StreamChainingExample {
  public static void main(String[] args) {
    List names = Arrays.asList("John", "Jane", "Jack", "Tom", "Jill");

    List result = names.stream()
                               .filter(n -> n.startsWith("J"))
                               .map(String::toUpperCase)
                               .sorted()
                               .collect(Collectors.toList());

    System.out.println(result);
  }
}

πŸ“˜ Detailed Explanation:

  • filter(): Filters elements based on a condition.
  • map(): Transforms each element.
  • sorted(): Sorts elements in natural order (can use comparator).
  • collect(): Gathers stream results into a collection.

πŸ› οΈ Use Cases:

  • Processing collections with multiple transformations in one line.
  • Improving performance by avoiding intermediate collections.
  • Writing expressive and readable data pipelines.