Source of EmptyStringElimination.java


  1: //EmptyStringElimination.java

  3: import java.util.ArrayList;
  4: import java.util.Arrays;
  5: import java.util.List;
  6: import java.util.stream.Collectors;

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

 17:         System.out.println("\n=============");
 18:         System.out.println("Using Java 7: ");
 19:         List<String> filteredList = new ArrayList<String>();
 20:         for (String string : strings)
 21:         {
 22:             if (!string.isEmpty())
 23:             {
 24:                 filteredList.add(string);
 25:             }
 26:         }
 27:         System.out.println
 28:         (
 29:             "List of strings with empty ones removed: "
 30:             + filteredList
 31:         );

 33:         System.out.println("\n=============");
 34:         System.out.println("Using Java 8: ");
 35:         System.out.println
 36:         (
 37:             "List of strings with empty ones removed: "
 38:             + strings
 39:             .stream()
 40:             .filter(string -> !string.isEmpty())
 41:             .collect(Collectors.toList())
 42:         );
 43:     }
 44: }
 45: /*  Output:

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

 49:     =============
 50:     Using Java 7:
 51:     List of strings with empty ones removed: [abc, bc, efg, abcd, jkl, mno]

 53:     =============
 54:     Using Java 8:
 55:     List of strings with empty ones removed: [abc, bc, efg, abcd, jkl, mno]
 56: */