Java 8 Stream Collectors.counting() exmaple

The Collectors.counting retuns a Collector that counts the number of elements in the stream.

Java 8 Stream Collectors.counting() exmaple

The example counts the number of elements in the list:


import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class JavaCollectToListEx {

    public static void main(String[] args) {

        List < String > programmingLanguages = new ArrayList < > ();
        programmingLanguages.add("C");
        programmingLanguages.add("C++");
        programmingLanguages.add("Java");
        programmingLanguages.add("Kotlin");
        programmingLanguages.add("Python");
        programmingLanguages.add("Perl");
        programmingLanguages.add("Ruby");

        // filter all four character words into a list
        long result = programmingLanguages.stream().collect(Collectors.counting());

        System.out.println(result);
    }
}

Output:

7

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments