Java Stream How to - Create Lambda to match string








Question

We would like to know how to create Lambda to match string.

Answer

//  www.  j av  a  2s .c o m
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Main {
  public static void main(String[] argv) throws Exception {
    List<String> argList = Arrays.asList("help", "v");

    Predicate<String> isHelp = (s) -> s.matches("(h|help)");
    Predicate<String> isVerbose = (s) -> s.matches("(v|verbose)");

    boolean needsHelp = argList.stream().anyMatch(isHelp);
    System.out.println(needsHelp);

    boolean verbose = argList.stream().anyMatch(isVerbose);
    System.out.println(verbose);
  }

}

The code above generates the following result.