Collectors counting() method in Java 8

Java 8Object Oriented ProgrammingProgramming

The counting() method of the Java 8 Collectors class returns a Collector accepting elements of type T that counts the number of input elements.

The syntax is as follows −

static <T> Collector<T,?,Long> counting()

Here, the parameter −

  • T − type of input elements

  • Long − This class value of the primitive type long in an object

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

import java.util.stream.Collectors;

The following is an example to implement counting() method in Java 8 −

Example

 Live Demo

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("25", "50", "75", "100", "125", "150", "200");
      long res = stream.collect(Collectors.counting());
      System.out.println("Count of elements in the stream = "+res);
   }
}

Output

Count of elements in the stream = 7
raja
Updated on 30-Jul-2019 22:30:25

Advertisements