Question: Is there a way to call a method on a lambda expression?

Consider following example where the reversed() method is called on MileageComparator:
`Collections.sort(cars, new MileageComparator().reversed());`

If I write MileageComparator as a Lambda Expression with a reversed() call however, I get an error when writing
`Collections.sort(cars, ((Car car1, Car car2) -> (int) (car2.getMileage() - car1.getMileage())).reversed());`
while it works fine without reversed.

I do know that I can simply exchange car1 and car2 for the same result, I would however like to know if a method call on a lambda expression is possible in general.

Answer: 
> 
> I would however like to know if a method call on a lambda expression is possible in general.
> 
> 
> 

It is not, because a lambda expression by itself is nothing.

The lambda expression is syntax sugar for implementing a functional interface. Without the interface defining the method signature, the lambda expression doesn't know what it is.

It's like creating an anonymous class using an undefined type name, e.g.

```
new Foo() {
    public void bar() {
        // This will not work
    }
}

```

That anonymous class will fail to compile if `Foo` doesn't exist.

Similarly, `(Car a) -> a.openDoor()` will fail to compile, because the compiler doesn't know what type is being implemented. To make it work, the compiler need to know which functional interface to implement, e.g.

```
Consumer<Car> x = (Car a) -> a.openDoor();

```

But the following will fail with error `Lambda expression needs an explicit target-type`:

```
var x = (Car a) -> a.openDoor();

```

When you wrap the lambda expression in parentheses and call a method on it, no functional interface can be inferred by the compiler, which is why this fails:

```
((Car a) -> a.openDoor()).accept(myCar)

```

You can however tell the compiler which interface to implement, by providing a cast:

```
((Consumer<Car>) (Car a) -> a.openDoor()).accept(myCar)

```
A couple of points.

You tried this and it didn't work.

```
       Collections.sort(cars, ((Car car1, Car car2) -> (int) (car2.getMileage() - 
                car1.getMileage())).reversed())

```

The Comparator is the same as the following:

```
       Comparator<Car> comp = ((car1, car2)->car1.getMileage() - car2.getMileage()).reversed();

```

Which won't compile either because the lambda on the right knows nothing about the `reversed()` method of the `Comparator`.

But you could have done this:

```
        Comparator<Car> comp = (car1, car2)->car1.getMileage() - car2.getMileage();

```

And then

```
       Collections.sort(cars, comp.reversed());

```

Because `comp` is a Comparator and knows about the `reversed()` method.

One final point. It is not a good idea to use `(a,b)-> a - b` because subtracting values will not always yield the expected results. It is better form to do `(a,b)-> (a > b) ? 1 : (a < b) ? -1 : 0`