Java Stream How to - Filter string by length and not null








Question

We would like to know how to filter string by length and not null.

Answer

/*from  w  w  w .  j  a v a 2  s . c o m*/
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class Main {

  public static void main(String[] args) {
    List<String> liste = Arrays.asList("CSS", "HTML", "Davut", null);

    liste.parallelStream()// Parallel stuff uses Fork-Join
        .filter(e -> (!Objects.equals(e, null))) // lazy & parallel
        .filter(e -> (e.length() > 3)) // lazy & parallel
        .forEach(e -> { // sequential & eagerly
              System.out.println("Bigger length than 3 in List: " + e);
            });
  }
}

The code above generates the following result.