Collectors toCollection(Supplier<C> collectionFactory) method in Java is used to create a Collection using Collector. It returns a Collector that accumulates the input elements into a new Collection, in the order in which they are passed.
public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory)
- Collection : The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered.
- Collector<T, A, R> : A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.
- T : The type of input elements to the reduction operation.
- A : The mutable accumulation type of the reduction operation.
- R : The result type of the reduction operation.
- Supplier : A functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
- collectionFactory : A Supplier which returns a new, empty Collection of the appropriate type.
Parameters: This method takes a mandatory parameter collectionFactory of type Supplier which returns a new, empty Collection of the appropriate type.
Return Value: This method returns a collector which collects all the input elements into a Collection, in encounter order.
Below given are some examples to illustrate the implementation of toCollection() in a better way:
[Geeks, GeeksClasses, for]
[2.5, 4, 6]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.