Java Streams - Stream collect(Collector collector) example








Stream collect(Collector<? super T,A,R> collector) performs a mutable reduction operation on the elements using a Collector.

Syntax

collect has the following syntax.

<R,A> R collect(Collector<? super T,A,R> collector)

Example

The following example shows how to use collect.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/* w ww.  j a va 2s. c  om*/
public class Main {
  public static void main(String[] args) {
    List<String> stringList = Arrays.asList("2","1","3","4");

     long m = stringList
              .stream()    
              .collect(Collectors.counting());
     System.out.println(m);
  }
}

The code above generates the following result.