Java 8 Lambda returning lambda part 2

        Function<Integer, Function<Integer, Integer>> f = i1 -> i2 -> i1 - i2;
        List<Integer> ints = Arrays.asList(1, 2, 3);
        Integer res = 0;
        for (int ii = ints.size() - 1; ii >= 0; ii--) {
            Integer t = ints.get(ii); // 3 // 2 // 1
            Function<Integer, Integer> ff = f.apply(t); // i2 -> 3 - i2 // i2 -> 2 - i2 // i2 -> 1 - i2
            res = ff.apply(res); // 3 - 0 = 3 // 2 - 3 = -1 // 1 - -1 = 2
            System.out.println("intermediate res=" + res);
        }
        System.out.println("final res=" + res); // 2

Output:

intermediate res=3
intermediate res=-1
intermediate res=2
final res=2
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