Java Stream How to - Check if all value in the list match a condition








Question

We would like to know how to check if all value in the list match a condition.

Answer

import java.util.ArrayList;
import java.util.List;
//from   w w w. ja  va 2  s.  c om
public class Main {

  public static void main(final String[] args) {
    List<String> stringCollection = new ArrayList<>();
    stringCollection.add("ddd2");
    stringCollection.add("aaa2");
    stringCollection.add("bbb1");
    stringCollection.add("aaa1");
    stringCollection.add("bbb3");
    stringCollection.add("ccc");
    stringCollection.add("bbb2");
    stringCollection.add("ddd1");


    boolean allStartsWithA = stringCollection
            .stream()
            .allMatch((s) -> s.startsWith("a"));

    System.out.println(allStartsWithA);      // false
  }

}

The code above generates the following result.