Java Streams - Stream collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner) example








Stream collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner) performs a mutable reduction operation on the elements of this stream.

Syntax

collect has the following syntax.

<R> R collect(Supplier<R> supplier,  BiConsumer<R,? super T> accumulator,  BiConsumer<R,R> combiner)

Example

The following example shows how to use collect.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
//ww  w  .ja  v a  2s . c o  m
public class Main {
  public static void main(String[] args) {
    Stream<String> s = Stream.of("a","b","c");
    
    List<String> names = s
        .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

    System.out.println(names);
  }
}

The code above generates the following result.