Java.Java8.How can I display the number of empty strings using the filter() method?

✅ Goal:

  • Use filter() to keep only empty strings.
  • Use count() to get the number of them.

🔹 Example:

import java.util.List;

public class EmptyStringCounter {
    public static void main(String[] args) {
        List<String> strings = List.of("hello", "", "world", "", "java", "");

        long count = strings.stream()
                            .filter(String::isEmpty)  // keep only empty strings
                            .count();                 // count them

        System.out.println("Number of empty strings: " + count);
    }
}

🔹 Output:

Number of empty strings: 3

✅ Breakdown:

  • filter(String::isEmpty): keeps only strings that are ""
  • count(): returns the total number of elements remaining after filtering
This entry was posted in Без рубрики. Bookmark the permalink.