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:
- Use
collect(Collectors.toList())
to convert a stream into a List. - Use
Collectors.toSet()
to collect elements into a Set. - Use
Collectors.toMap()
to build a Map from key/value pairs. - 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.