Sobes.tech
Middle

What does the collect method do in Java?

sobes.tech AI

Answer from AI

The collect method in Java Stream API performs a mutable reduction of stream elements into a single result object. It takes a Collector as an argument and allows aggregating data in various ways, such as collecting elements into collections, grouping them, or applying aggregation functions (summing, averaging, etc.).

Main components of Collector:

  • supplier(): Creates a new, empty result container.
  • accumulator(): Adds the current stream element to the result container.
  • combiner(): Merges two result containers (used in parallel streams).
  • finisher(): Applies a final transformation to the result container (optional).

Popular implementations of Collector are provided by the Collectors class:

  • toList(), toSet(), toMap(): Collects elements into a List, Set, Map respectively.
  • joining(): Concatenates string elements.
  • groupingBy(): Groups elements based on a given criterion.
  • counting(), summingInt(), averagingDouble(): Counting, summing, averaging.

Example of using collect to gather elements into a list:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CollectExample {

    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

        List<String> collectedNames = names.stream()
                                          .collect(Collectors.toList()); // Collect into List

        System.out.println(collectedNames);
    }
}