What does the arrow operator, '->', do in Java?

Mike Rylander picture Mike Rylander · Feb 28, 2013 · Viewed 217.8k times · Source

While hunting through some code I came across the arrow operator, what exactly does it do? I thought Java did not have an arrow operator.

return (Collection<Car>) CollectionUtils.select(listOfCars, (arg0) -> {
        return Car.SEDAN == ((Car)arg0).getStyle();
});

Details: Java 6, Apache Commons Collection, IntelliJ 12

Update/Answer: It turns out that IntelliJ 12 supports Java 8, which supports lambdas, and is "folding" Predicates and displaying them as lambdas. Below is the "un-folded" code.

return (Collection<Car>) CollectionUtils.select(listOfCars, new Predicate() {
    public boolean evaluate(Object arg0) {
        return Car.SEDAN == ((Car)arg0).getStyle();
    }
});

Answer

&#211;scar L&#243;pez picture Óscar López · Feb 28, 2013

That's part of the syntax of the new lambda expressions, to be introduced in Java 8. There are a couple of online tutorials to get the hang of it, here's a link to one. Basically, the -> separates the parameters (left-side) from the implementation (right side).

The general syntax for using lambda expressions is

(Parameters) -> { Body } where the -> separates parameters and lambda expression body.

The parameters are enclosed in parentheses which is the same way as for methods and the lambda expression body is a block of code enclosed in braces.