Java Stream How to - Nest Predicate into Function








Question

We would like to know how to nest Predicate into Function.

Answer

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
//from   w  w w.  j  a  va 2 s  .  c o m
public class Main {

  public static void main(String[] args) {
    List<String> names = Arrays.asList("XML", "HTML", "Java", "Javascript", "CSS", "C");

    Function<String, Predicate<String>> startsWithLetter = letter -> name -> name.startsWith(letter);

    names.stream()
            .filter(startsWithLetter.apply("J"))
            .forEach(System.out::println);
  }
}

The code above generates the following result.