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

Updated on: 30-Jul-2019

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements