-4

Tried to replace lambdas with anonymous class in Stream API (below code) and it works fine. I want to understand how the parameter required for the test(T t) method is getting generated from.

Lambda

                list.stream()
                .map(String::length)
                .filter(t->t>4).count();

Anonymous class

                list.stream()//line1
                .map(String::length)
                .filter(new Predicate<Integer>() {
                    @Override
                    public boolean test(Integer t) {//line 5
                        
                        return t>4;
                    }
                }).count();

While using lambdas we pass the parameter using the lambda notation, but I dont understand how the Integer t at line 5 is getting generated from. Is it due to the Fluent API in Stream or due to the functional interface(lambda)?

Edit : I am clear about lambda version, dont understand how the version with anonymous class is working? To put in another way, would it work in Java 1.7 (provided we wrote something similar to Stream API, we just wont have lambdas).

Edit : For anyone confused like I was, please look at https://github.com/fmcarvalho/quiny , simplified implementation of Stream API by some smart guy

javaAndBeyond
  • 520
  • 1
  • 9
  • 26
  • 1
    Yes, it would have worked in Java 7 with anonymous classes. (Some third-party libraries did exactly that, e.g. Guava's FluentIterable.) – Louis Wasserman Oct 23 '20 at 18:40
  • OK Thanks. So its the Fluent API thats responsible for this functionality? – javaAndBeyond Oct 23 '20 at 18:42
  • 1
    I mean, it's not really the "fluent API" that's responsible. It's just...how those language features work. – Louis Wasserman Oct 23 '20 at 19:04
  • Ok, which feature in java, Method chaining? But I dont see this keyword being used here, which is used usualy in method chaining. – javaAndBeyond Oct 23 '20 at 19:07
  • 1
    Method chaining isn't actually a language feature, it's just a way of using the language. It's not actually related to the use of the `Predicate` at all. The use of `this` isn't necessary to achieve method chaining, either. – Louis Wasserman Oct 23 '20 at 19:42
  • I understand method chaining is just a way of de-referencing. Could you please explain what feature is causing, if not Fluent API? – javaAndBeyond Oct 23 '20 at 19:56
  • ...causing _what_? There isn't anything going on here more significant than anonymous inner classes or lambdas implementing an interface. – Louis Wasserman Oct 23 '20 at 21:24

1 Answers1

1

When you write t -> t > 4, Java automatically infers the type of this lambda -- it must be a Predicate<Integer>, given that it's being passed to filter on a Stream<Integer> -- and then automatically figures out that it must be (Integer t) -> t > 4.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413