Java 8 Lambda returning lambda

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

public class LamdaReturningLambda {

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("Bob", "Alice");

        // first approach
        strings
            .stream()
            .filter(e -> e.contains("i"))
            .filter(e -> e.contains("c"))
            .forEach(System.out::println);


        // second approach
        Predicate<String> contains_i = name -> name.contains("i");
        Predicate<String> contains_c = name -> name.contains("c");

        strings
            .stream()
            .filter(contains_i)
            .filter(contains_c)
            .forEach(System.out::println);


        // third approach
        strings
            .stream()
            .filter(containsString("i"))
            .filter(containsString("c"))
            .forEach(System.out::println);

        // fourth approach
        Function<String, Predicate<String>> containsFunc = s -> name -> name.contains(s); // lambda returning predicate
        strings
            .stream()
            .filter(containsFunc.apply("i"))
            .filter(containsFunc.apply("c"))
            .forEach(System.out::println);
    }

    static Predicate<String> containsString(String s) {
        return name -> name.contains(s);
    }

}

Output:

Alice
Alice
Alice
Alice
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s