- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java streams counting() method with examples
Count the number of elements in the stream using the Java streams counting() method. Following is an example to implement the Java Streams counting() method −
Example
import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<String> stream = Stream.of("Kevin", "Jofra","Tom", "Chris", "Liam"); // count long count = stream.collect(Collectors.counting()); System.out.println("Number of elements in the stream = "+count); } }
Output
Number of elements in the stream = 5
Let us see another example wherein we have stream of integer elements −
Example
import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<Integer> stream = Stream.of(5, 10, 20, 40, 80, 160); // count long count = stream.collect(Collectors.counting()); System.out.println("Number of elements in the stream = "+count); } }
Output
Number of elements in the stream = 6
Advertisements