Source of CountingEmptyStrings.java


  1: //CountingEmptyStrings.java

  3: import java.util.Arrays;
  4: import java.util.List;

  6: public class CountingEmptyStrings
  7: {
  8:     public static void main(String args[])
  9:     {
 10:         //We will count the empty strings in the following list of strings:
 11:         List<String> strings
 12:             = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl", "mno");
 13:         System.out.println("\nList of strings: " + strings);

 15:         System.out.println("\n=============");
 16:         System.out.println("Using Java 7: ");
 17:         int count = 0;
 18:         for (String string : strings)
 19:         {
 20:             if (string.isEmpty())
 21:             {
 22:                 count++;
 23:             }
 24:         }
 25:         System.out.println("Number of empty strings: " + count);

 27:         System.out.println("\n=============");
 28:         System.out.println("Using Java 8: ");
 29:         System.out.println
 30:         (
 31:             "Number of empty strings: " + strings
 32:             .stream()
 33:             .filter(string -> string.isEmpty())
 34:             .count()
 35:         );
 36:     }
 37: }
 38: /*  Output:

 40:     List of strings: [abc, , bc, efg, abcd, , jkl, mno]

 42:     =============
 43:     Using Java 7:
 44:     Number of empty strings: 2

 46:     =============
 47:     Using Java 8:
 48:     Number of empty strings: 2
 49: */