Count non empty strings

Similar to filtering a collection or counting the number of occurrences in a list this example will count the number of non empty strings in a collection. In a related example we demonstrate count non null or empty elements in arraylist using groovy.

Straight up Java

@Test
public void count_non_empty_strings_java () {
    
    List<String> valentineSayings = new ArrayList<String>();
    valentineSayings.add("crush");
    valentineSayings.add("");
    valentineSayings.add("blind date");
    valentineSayings.add("puppy luv");
    valentineSayings.add("mr right");
    valentineSayings.add("");
    valentineSayings.add("first kiss");
    valentineSayings.add("4 ever yours");
    
    List<String> string = new ArrayList<String>();
    string.add("");
    
    valentineSayings.removeAll(string); 

    assertEquals(6, valentineSayings.size());
}

Java 8

@Test
public void count_non_empty_strings_java_8 () {

    List<String> valentineSayings = new ArrayList<>();
    valentineSayings.add("crush");
    valentineSayings.add("");
    valentineSayings.add("blind date");
    valentineSayings.add("puppy luv");
    valentineSayings.add("mr right");
    valentineSayings.add("");
    valentineSayings.add("first kiss");
    valentineSayings.add("4 ever yours");
    
    long count = valentineSayings.stream().filter(x -> !x.isEmpty()).count();
    
    assertEquals(6, count);
}

Google Guava

@Test
public void count_non_empty_strings_guava () {
    
    List<String> valentineSayings = Lists.newArrayList(
            "crush", 
            "", 
            "blind date", 
            "puppy luv", 
            "mr right", 
            "", 
            "first kiss", 
            "4 ever yours");
    
    int count = FluentIterable.from(valentineSayings).filter(new Predicate<String>() {
        @Override
        public boolean apply(String input) {
            return !input.isEmpty();
        }
    }).size();
    
    assertEquals(6, count);      
}