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

2019-01-02 20:22发布

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();
    }
});

4条回答
路过你的时光
2楼-- · 2019-01-02 21:21

This one is useful as well when you want to implement an interface

Runnable r = ()-> System.out.print("Run method");

is equivalent to

Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.print("Run method");
            }
        };
查看更多
泛滥B
3楼-- · 2019-01-02 21:22

It's a lambda expression.

It means that, from the listOfCars, arg0 is one of the items of that list. With that item he is going to do, hence the ->, whatever is inside of the brackets.

In this example, he's going to return a list of cars that fit the condition

Car.SEDAN == ((Car)arg0).getStyle();
查看更多
若你有天会懂
4楼-- · 2019-01-02 21:25

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 actual expression (right side).

查看更多
流年柔荑漫光年
5楼-- · 2019-01-02 21:25

I believe, this arrow exists because of your IDE. IntelliJ IDEA does such thing with some code. This is called code folding. You can click at the arrow to expand it.

查看更多
登录 后发表回答