Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Java 8 FAQ: Top Questions

13. What is the purpose of the Stream's collect() method in Java 8?

The collect() method in Java 8 is a terminal operation used to transform the elements of a stream into a different form, such as a List, Set, Map, or a custom result container. It uses Collector implementations to define the transformation strategy.

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

  1. Use collect(Collectors.toList()) to convert a stream into a List.
  2. Use Collectors.toSet() to collect elements into a Set.
  3. Use Collectors.toMap() to build a Map from key/value pairs.
  4. Use Collectors.joining() to concatenate elements into a String.

πŸ“₯ Example Input:

List names = Arrays.asList("Tom", "Jerry", "Spike");

String result = names.stream()
                     .collect(Collectors.joining(", "));

πŸ† Expected Output:

Tom, Jerry, Spike

βœ… Java 8 Solution:

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

public class StreamCollectExample {
  public static void main(String[] args) {
    List names = Arrays.asList("Tom", "Jerry", "Spike");

    String result = names.stream()
                         .collect(Collectors.joining(", "));

    System.out.println(result);
  }
}

πŸ“˜ Detailed Explanation:

  • collect(): Triggers stream evaluation and returns a result.
  • toList(), toSet(): Useful for converting streams to collections.
  • joining(): Joins strings with delimiters.
  • toMap(): Transforms elements into key-value pairs for a map.

πŸ› οΈ Use Cases:

  • Converting processed data into a final container type.
  • Creating summaries or aggregates from stream elements.
  • Building reports, indexes, or lookup tables from raw data.