The collect() method in Java is a part of the java.util.stream.Stream interface. In this guide, we will learn how to use collect() method in Java with practical examples and real-world use cases to better understand its functionality.
Table of Contents
- Introduction
collect()Method Syntax- Understanding
collect() - Examples
- Basic Usage with Collectors
- Using Custom Collector
- Real-World Use Case
- Conclusion
Introduction
The Stream.collect() method in Java gathers elements from a stream into collections like List or Set. It’s often the final step in stream processing.
Commonly, collect() is used with Collectors.toList() or Collectors.toSet() to convert a stream into a List or Set for easier data handling.
Additionally, collect() can be customized to gather elements into more complex structures like Map, providing flexibility in how stream data is accumulated.
collect() Method Syntax
There are two main overloads of the collect() method:
- Using a
Collector:<R, A> R collect(Collector<? super T, A, R> collector) - Using a supplier, accumulator, and combiner:
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)
Parameters:
collector: TheCollectordescribing the reduction.supplier: A function that provides a new mutable result container.accumulator: An associative, non-interfering, stateless function for incorporating an additional element into a result container.combiner: An associative, non-interfering, stateless function for combining two result containers.
Returns:
- The result of the reduction.
Throws:
- This method does not throw any exceptions.
Understanding collect()
The collect() method is used to gather the elements of a stream into a container, such as a List, Set, or Map. It is highly flexible, allowing you to define custom reduction operations using a combination of supplier, accumulator, and combiner functions.
Examples
Basic Usage with Collectors
To demonstrate the basic usage of collect(), we will create a Stream of strings and use collect() to accumulate its elements into a List.
Example
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectExample {
public static void main(String[] args) {
Stream<String> stream = Stream.of("apple", "banana", "cherry");
// Collect the elements into a List
List<String> list = stream.collect(Collectors.toList());
// Print the list
System.out.println(list);
}
}
Output:
[apple, banana, cherry]
Using Custom Collector
This example shows how to use collect() with custom supplier, accumulator, and combiner functions to accumulate elements into a StringBuilder.
Example
import java.util.stream.Stream;
public class CustomCollectorExample {
public static void main(String[] args) {
Stream<String> stream = Stream.of("apple", "banana", "cherry");
// Collect the elements into a StringBuilder
StringBuilder stringBuilder = stream.collect(
StringBuilder::new, // Supplier
(sb, s) -> sb.append(s).append(", "), // Accumulator
StringBuilder::append // Combiner
);
// Print the StringBuilder
System.out.println(stringBuilder);
}
}
Output:
apple, banana, cherry,
Real-World Use Case
Example : Collecting Employee Names into a List
In real-world applications, the collect() method can be used to collect employee names into a list from a stream of employee objects.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class EmployeeCollectExample {
static class Employee {
String name;
int age;
Employee(String name, int age) {
this.name = name;
this.age = age;
}
String getName() {
return name;
}
}
public static void main(String[] args) {
Stream<Employee> employeeStream = Stream.of(
new Employee("Alice", 30),
new Employee("Bob", 25),
new Employee("Charlie", 35)
);
// Collect employee names into a List
List<String> employeeNames = employeeStream.map(Employee::getName).collect(Collectors.toList());
// Print the list of employee names
System.out.println(employeeNames);
}
}
Output:
[Alice, Bob, Charlie]
Example 2: Grouping Products by Category
A common use case for the collect() method is to group data by certain attributes. Let’s group products by their category using Collectors.groupingBy():
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GroupingProductsExample {
static class Product {
String name;
String category;
Product(String name, String category) {
this.name = name;
this.category = category;
}
String getCategory() {
return category;
}
@Override
public String toString() {
return name;
}
}
public static void main(String[] args) {
Stream<Product> productStream = Stream.of(
new Product("Laptop", "Electronics"),
new Product("Shirt", "Clothing"),
new Product("Phone", "Electronics"),
new Product("Jeans", "Clothing")
);
// Group products by category
Map<String, List<Product>> productsByCategory = productStream.collect(Collectors.groupingBy(Product::getCategory));
// Print the grouped products
System.out.println(productsByCategory);
}
}
Output:
{Electronics=[Laptop, Phone], Clothing=[Shirt, Jeans]}
Example 3: Counting Elements in a Stream
Another real-world scenario is counting elements in a stream. Here’s how to use Collectors.counting() to count the number of items:
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CountingElementsExample {
public static void main(String[] args) {
Stream<String> stream = Stream.of("apple", "banana", "cherry", "apple");
// Count the number of elements in the stream
long count = stream.collect(Collectors.counting());
// Print the count
System.out.println("Number of elements: " + count);
}
}
Output:
Number of elements: 4
Conclusion
The Stream.collect() method is used to perform a mutable reduction operation on the elements of the stream, gathering them into a container such as a List, Set, or Map. This method is particularly useful for collecting and transforming stream elements.