Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to count element after filtering in Java?
Let’s say the following is the String List:
List<String> list = new ArrayList<>();
list.add("Tom");
list.add("John");
list.add("David");
list.add("Paul");
list.add("Gayle");
list.add("Narine");
list.add("Joseph");
Now, let’s say you need to filter elements beginning with a specific letter. For that, use filter() and startsWith():
long res = list
.stream()
.filter((s) -> s.startsWith("J"))
.count();
We have also counted the elements above after filtering using count().
The following is an example to count element after filtering in Java:
Example
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(final String[] args) {
List<String> list = new ArrayList<>();
list.add("Tom");
list.add("John");
list.add("David");
list.add("Paul");
list.add("Gayle");
list.add("Narine");
list.add("Joseph");
long res = list .stream() .filter((s) -> s.startsWith("J")) .count();
System.out.println("How many strings begin with letter J? = "+res);
}
}
Output
How many strings begin with letter J? = 2
Advertisements