Collectors toCollection() method in Java



In this article, we will learn the Collectors.toCollection() method in Java, an essential tool for collecting elements into a specific type of collection, such as a List, Set, or any other collection type.

Java 8 introduced a new, powerful feature called Streams, which enables functional-style programming to process sequences of elements. One of the key utilities in the Streams API is the Collectors class.

What is the Collectors.toCollection() Method?

The Collectors.toCollection() method is a static method in the Collectors class that allows you to collect elements from a stream into a custom collection.

public static <T, A, R> Collector<T, A, R> toCollection(Supplier<R> collectionFactory)

Here are the parameters ?

  • T: The type of elements in the stream.
  • A: The accumulation type (usually a mutable container).
  • R: The resulting collection type (the final result of the collection).
  • collectionFactory: A Supplier that provides the collection where elements should be accumulated.

How to Use Collectors.toCollection()?

The toCollection() method takes a Supplier that provides a collection type and collects the elements of the stream into that specific collection. This is especially useful when you want to use a collection type other than List or Set.

To work with Collectors class in Java, import the following package ?

import java.util.stream.Collectors;

Example

The following is an example to implement toCollection() method in Java ?

import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("20", "50", "80", "100", "130", "150", "200");
      Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new));
      System.out.println("Collection = "+collection);
   }
}

Output

Collection = [100, 130, 150, 20, 200, 50, 80]

Collecting into a Custom List

In this example, we'll use Collectors.toCollection() to collect elements from a stream into an ArrayList.

  • We start with a list of integers.
  • We filter the stream to only include even numbers.
  • Using Collectors.toCollection(ArrayList::new), we collect the filtered stream into an ArrayList.

This method allows you to customize the collection type, making it more flexible than just using toList().

Example

The following is an example to implement toCollection() method in a custom list using Java ?

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

public class ToCollectionExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // Using toCollection to collect into a custom ArrayList
        List<Integer> collectedList = numbers.stream()
                 .filter(num -> num % 2 == 0)
                 .collect(Collectors.toCollection(ArrayList::new));

        System.out.println(collectedList);  
    }
}

Output

[2, 4]

Collecting into a HashSet

Now, let's see how we can use Collectors.toCollection() to collect elements into a HashSet instead of the default List.This method is particularly useful when the collection type needs to have unique elements or other specific characteristics that are not provided by List.

Example

The following is an example to implement toCollection() method in a custom HashSet using Java ?

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

public class HashSetCollectionExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 5);

        // Using toCollection to collect into a HashSet
        Set<Integer> collectedSet = numbers.stream()
                  .filter(num -> num % 2 == 0) 
                  .collect(Collectors.toCollection(HashSet::new));

        System.out.println(collectedSet);   
    }
}

Output

[2, 4]

Conclusion

The Collectors.toCollection() method in Java 8 is a versatile and powerful tool for customizing the collection type when working with streams. It allows you to collect elements into any collection, providing flexibility and control over the data structure used in your application.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2024-12-31T22:02:20+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements