Close

Java 8 Streams - Collectors.toCollection Examples

Java 8 Streams Java Java API 


java.lang.Objectjava.lang.Objectjava.util.stream.Collectorsjava.util.stream.CollectorsLogicBig

The static method, Collectors.toCollection() returns a Collector which produces a new Collection, populated with the stream elements.

<T,C extends Collection<T>> Collector<T,?,C> toCollection(Supplier<C> collectionFactory)

Parameters

collectionFactory: is a Supplier function which returns a new instance of the desired collection implementation.


Examples


package com.logicbig.example.collectors;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ToCollectionExample {
public static void main (String[] args) {
Stream<BigDecimal> s = Stream.iterate(
BigDecimal.ONE, bigDecimal ->
bigDecimal.add(BigDecimal.ONE))
.limit(10)
.peek(System.out::println);

LinkedList<BigDecimal> l = s.collect(
Collectors.toCollection(LinkedList::new));
System.out.println(l);
}
}

Output

1
2
3
4
5
6
7
8
9
10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Original Post




See Also